利用 node Express 框架实现get,post请求的前后端交互

安装 Express 并将其保存到依赖列表中:

$ cnpm install express --save

body-parser - node.js 中间件,用于处理 JSON, Raw, Text 和 URL 编码的数据。

$ cnpm install body-parser --save

node后台代码 node.js

var express = require('express');
var bodyParser = require('body-parser');
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')
    //这段仅仅为了方便返回json而已
    res.header("Content-Type", "application/json;charset=utf-8");
    if (req.method == 'OPTIONS') {
        //让options请求快速返回
        res.sendStatus(200);
    } else {
        next();
    }
});
// 创建 application/x-www-form-urlencoded 编码解析
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function (req, res) {
    var getObj = req.body;
    console.log(getObj);
    res.send(JSON.stringify(getObj));
})
app.get('/index', function (req, res) {
    var getObj = req.query;
    console.log(getObj);
    res.send(JSON.stringify(getObj));
})
var server = app.listen(8081, function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log("应用实例,访问地址为 http://%s:%s", host, port)
})

启动后台 node node.js
前台发送请求:
POST请求

$.ajax({
    type: 'post',
    dataType: 'json',
    url: 'http://localhost:8081',
    data: {
        name: 'zhanghao',
        gongzi: '20000'
    },
    success: function (data) {
        console.log(data);
    },
    error: function (data) {
        console.log(data);
    }
})

GET请求

$.ajax({
    type: 'get',
    dataType: 'json',
    url: 'http://localhost:8081/index',
    data: {
        name: 'zhanghao',
        gongzi: '20000'
    },
    success: function (data) {
        console.log(data);
    },
    error: function (data) {
        console.log(data);
    }
})

你可能感兴趣的:(利用 node Express 框架实现get,post请求的前后端交互)