node接口编写

var express = require("express")
var bodyParser = require('body-parser');   //body解析
var multiparty = require('multiparty'); //从node_modules
var app = express();
var path = require("path");

var arr = []

var allowCrossDomain = function (req, res, next) {
 res.header('Access-Control-Allow-Origin', '*');//自定义中间件,设置跨域需要的响应头。
 res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');  //允许任何方法
 res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token');   //允许任何类型
 next();
};

app.use(allowCrossDomain);//运用跨域的中间件
//app.use(bodyParser.text());//运用中间件,对请求体的文本进行解析
app.use(bodyParser.json())   //// 创建 application/json 解析
app.use(bodyParser.urlencoded({extended: true})) // 创建 application/x-www-form-urlencoded 解析

app.get("/", function(req, res){
    res.send('index')
})
app.get("/data/query", function(req, res){
    res.send(JSON.stringify(arr));
})
// 规定了data/后面就是参数
app.get("/api/data/:name-:age", function(req, res){
    console.log(req.body, req.query, req.params)
    res.send(JSON.stringify(arr));
})
//post  put
app.post("/data/add", function(req, res){
    console.log(req.body, req.query, req.params);
    arr.push(req.body)
    res.send(JSON.stringify(arr));
})
//formdata数据格式
app.post("/api/data/form", function(req, res) {
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {
           console.log(req.body, req.query, fields)
           res.send(JSON.stringify(fields));
    })
})
//跨域第三种  jsonp
app.get("/api/jsonp", function(req, res){
    var data = {name: "jsonp数据"} //返回数据
    data = JSON.stringify(data); //转字符串
    //var callback = `handleResponse(${data})`;
    var callback = `${req.query.callback}(${data})`; //函数名+数据
    console.log(callback)
    res.send(callback);
})
app.listen(3000, function(){console.log("Server started on port 3000.")});

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