使用說(shuō)明
proxy(host, options);
host 參數(shù)選項(xiàng)
const proxy = require('express-http-proxy')
proxy('http://google.com')
or
function selectProxyHost() {
return (new Date() % 2) ? 'http://google.com' : 'http://altavista.com';
}
proxy(selectProxyHost)
options參數(shù)選項(xiàng)
const httpProxy = require('express-http-proxy')
const app = express();
const userServiceProxy = httpProxy('http://google.com', {
//過(guò)濾器,指定類型的轉(zhuǎn)發(fā)(可選)
filter: function (req, res) {
return req.method == 'GET';
},
//請(qǐng)求路徑解析,轉(zhuǎn)換一下路徑(可選)
proxyReqPathResolver: function (req) {
var parts = req.url.split('?');
var queryString = parts[1];
var updatedPath = parts[0].replace(/test/, 'tent');
return updatedPath + (queryString ? '?' + queryString : '');
},
//處理響應(yīng)(可選)
userResDecorator: function (proxyRes, proxyResData, userReq, userRes) {
data = JSON.parse(proxyResData.toString('utf8'));
data.newProperty = 'exciting data';
return JSON.stringify(data);
},
//處理請(qǐng)求(可選)
proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
// you can update headers
// proxyReqOpts.headers['Content-Type'] = 'text/html';
// you can change the method
// proxyReqOpts.method = 'GET';
return proxyReqOpts;
},
//處理請(qǐng)求body(可選)
proxyReqBodyDecorator: function (bodyContent, srcReq) {
console.log(bodyContent);
return bodyContent;
},
//處理請(qǐng)求頭(可選)
userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) {
// recieves an Object of headers, returns an Object of headers.
return headers;
},
//自定義錯(cuò)誤(可選)
proxyErrorHandler: function (err, res, next) {
next(err);
}
})
認(rèn)證、限速等一系列中間件
app.use((req, res, next) => {
next()
})
// 代理請(qǐng)求
app.get('/test/*', (req, res, next) => {
userServiceProxy(req, res, next)
})
`http://localhost:3000/test/*` 代理到 `http://google.com/tent/*`上