前台页面:
$.get("/api/hello?name=leyi",function(rps){
console.info(rps);
});
node中间层(比如匹配api开头的所有请求):
var express = require('express');
var qs = require("qs")
var http = require("http");
var querystring = require('querystring');
app.all(//api/, function(req, res) {
let strData = qs.stringify(req.body); //请求体中的数据(比如post提交的数据)
let options = {
host: 'localhost', //后台请求地址
port: 8081,
path: req.url.substr(4),
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': strData.length
}
};
options.headers = Object.assign(options.headers, req.headers); //带上客户端请求头(包含cookie之类的东西)
let httpRequest = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
let _data = '';
res.on('data', function(chunk) {
_data += chunk;
});
res.on('end', function() {
sendData(_data);
});
});
httpRequest.write(strData); //写入数据到请求主体
httpRequest.end();
function sendData(data) {
res.send(data);
}
});
node后台:
var express = require('express');
var app = express();
var querystring=require("querystring");
app.post("/hello", function(req, res) {
console.info("req.headers", req.headers); //node中间层带来的请求头
console.info("req.query", req.query); //url上的查询参数
let data = '';
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
data = decodeURI(data);
console.log("data", data);
let dataObject = querystring.parse(data);
console.log("dataObject", dataObject);
});
res.json({ "result": "hello world!" });
});