基于node.js及express实现中间件,实现post、get

首先,当然是有必要的环境,安装node,这个我就不多说了。

依赖模块:

"express": "^4.13.4",
"request": "^2.72.0",
"body-parser": "^1.13.3",

页面
 $.ajax({
            type: "post",
            url: "/api",
            contentType: "application/json",    
            //data: {"UserName":"struggle","password":123456},  //普通数据
            data: JSON.stringify({"formdata":{"UserName":"struggle","password":123456}}),       //这里为了应付需要传复杂的json数据
            success:function(msg){
                console.log(msg);
            }
        });


服务端:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// 解析json,need it...
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());                    

app.post('/api', function(req, res,next){
    console.log('post-test');
    console.log(req.body.formdata);  
    var request = require('request');
    request.post('http://192.168.1.220:8094/User/Login',
        {form:req.body.formdata},
        function(err, response, body){
            res.send(body);   //返回的数据
        }
    );
});

app.use(express.static(path.join(__dirname, '/')))

app.listen(8080);    
console.log('Listening on port 8080');  
原文地址:https://www.cnblogs.com/wteng/p/5583972.html