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>
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34117170/article/details/79959648
个人分类: nodejs
所属专栏: web前端进阶
上一篇顶部进度条
下一篇json在html页面上高亮显示
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭