使用node搭建服务器并且写一个简单的接口、调接口

2019-02-14  本文已影响0人  努力努力再努力_g
var express=require('./node_modules/express');
var app =express();

//设置跨域访问
app.all('*', function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "X-Requested-With");
   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
   res.header("X-Powered-By",' 3.2.1');
   res.header("Content-Type", "application/json;charset=utf-8");
   next();
});



var questions=[
{
data:213,
num:444,
age:12
},
{
    data:456,
    num:678,
    age:13
    }];

    //写个接口123
    app.get('/123',function(req,res){
    res.status(200),
    res.json(questions)
    });

    //配置服务端口
    var server = app.listen(3000, function () {

    var host = server.address().address;

     var port = server.address().port;

        console.log('Example app listening at http://%s:%s', host, port);
    })

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="node">

    </div>

</body>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
    var nodeData;
    $.ajax({
        type: 'get',
        url: 'http://localhost:3000/123',
        success: function (data) {
            console.log(data);
            nodeData = data;
            for(var i=0;i<data.length;i++){
                $("#node").append(`<div>data:${data[i].data}</div><div>num:${data[i].num}</div><div>age:${data[i].age}</div><br>`)
            }
            
        },
        error: function () {
            console.log('error');
        }
    })    
</script>
</html>

数据结果


image.png
上一篇 下一篇

猜你喜欢

热点阅读