nodejs写api给前端调用

1.npm init 生成package.json文件
2. 安装依赖
npm install express –save
npm install body-parser –save
3.新建app.js
4.新建index.html
代码如下:

服务器端
app.js

var express=require('express');
var app =express();
var bodyParser = require('body-parser'); 
//引用bodyParser 这个不要忘了写
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//设置跨域访问
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)
    });
app.post('/wdltest',function(req,res){
    console.log(req.stack);
    console.log(req.body);
    console.log(req.url);
    console.log(req.query);
    res.json(req.body)
})
//配置服务端口
var server = app.listen(3001, function () {

    var host = server.address().address;

     var port = server.address().port;

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

//前端调用
index.html

<!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>
     <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
    <script>
        $(function(){
            console.log(1);
            //get请求
            $.ajax({
                type:'get',
                url:'http://localhost:3001/123',
                success:function(data){
                    console.log(data);
                },
                error:function(err){
                    console.log(err)
                }
            })
            //post请求
            $.ajax({
                type:'post',
                url:'http://localhost:3001/wdltest',
                data:{name:'wdl',pass:'123'},
                success:function(data){
                    console.log(data);
                },
                error:function(err){
                    console.log(err)
                }
            })
        })
    </script>
</body>
</html>
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值