通常我们常用的请求方法只有GET、POST、PUT和DELETE,所以在此只介绍这四种和文件上传的代理方式
在此我们使用request.js第三方模块实现
GET(DELETE同GET,将request方法改为DELETE即可)
const request = require('request');
const url = require('url');
test: function (req, res, next) {
let curl = url.parse(req.url);
let search= curl.search;
curl = "http:/localhost:8080/api/get"+search;
try {
req.pipe(request({
method: 'GET',
uri: curl
})).pipe(res);
} catch (e) {
next(e);
}
}
POST(PUT同POST,将request方法改为put即可)
const request = require('request');
const url = require('url');
test: function (req, res, next) {
let curl= url.parse(req.url);
let search= curl.search;
curl = "http://localhost:8080/api/post"+search;
let body = req.body;
try {
request.post({
uri: curl,
form: body
}).pipe(res);
} catch (e) {
next(e);
}
}
代理文件上传
const request = require('request');
const url = require('url');
upload: function (req, res, next) {
let curl= url.parse(req.url);
let search= curl.search;
curl = "http://localhost:8080/api/upload"+search;
try {
req.pipe(request({
method: 'POST',
uri: curl
})).pipe(res);
} catch (e) {
next(e);
}
}