node.js 接口编写

const express  = require('express');
var bodyParser = require("body-parser");  //post 请求需要
const app = express();
//全局设置
app.use(bodyParser.urlencoded({ extended: false }));   //post需要
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,OP0TIONS");
    res.header("X-Powered-By", "3.2.1");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
//接口编写
app.get('/del',function(req,res){
    let data= req.query;   //get传过来的参数
    res.status(200)
    res.json({name:'nihao'})
})
app.post('/add',function(req,res){
    let data= req.body;   //post传过来的参数
    console.log(req)
    res.status(200)
    res.json({name:'nihao'})
})
var server = app.listen(3000,function(){
    let host = server.address().address;
    let port = server.address().port;
    console.log("Example app listening at http://%s:%s", host, port)
})

你可能感兴趣的:(node.js 接口编写)