express-http-proxy是一個(gè)express代理中間件鞠值,其用法如下:
安裝
$ npm install express-http-proxy --save
用法
proxy(host, options);
例如播歼,將路由為'/proxy'的請(qǐng)求轉(zhuǎn)發(fā)至‘www.google.com’:則可用下列語句實(shí)現(xiàn)
var proxy = require('express-http-proxy');
var app = require('express')();
app.use('/proxy', proxy('www.google.com'));
Options
forwardPath
forwardPath選項(xiàng)用于在代理請(qǐng)求之前修改路徑
var proxy = require('express-http-proxy');
var app = require('express')();
app.use('/proxy', proxy('www.google.com', {
forwardPath: function(req, res) {
return require('url').parse(req.url).path;
}
}));
forwardPathAsync
forwardPathAsync選項(xiàng)用于在發(fā)送代理請(qǐng)求之前之前源请,使用Promise異步修改請(qǐng)求路徑
app.use(proxy('httpbin.org', {
forwardPathAsync: function() {
return new Promise(function(resolve, reject) {
// ...
// eventually
resolve( /* your resolved forwardPath as string */ )
});
}
}));
filter
filter選項(xiàng)主要用于篩選哪些請(qǐng)求可以被代理轉(zhuǎn)發(fā),例如,你只想轉(zhuǎn)發(fā)get請(qǐng)求
app.use('/proxy', proxy('www.google.com', {
filter: function(req, res) {
return req.method == 'GET';
},
forwardPath: function(req, res) {
return require('url').parse(req.url).path;
}
}));
intercept
intercept選項(xiàng)用于在將響應(yīng)返回給客戶端之前舔庶,對(duì)響應(yīng)做處理
app.use('/proxy', proxy('www.google.com', {
intercept: function(rsp, data, req, res, callback) {
// rsp - original response from the target
data = JSON.parse(data.toString('utf8'));
callback(null, JSON.stringify(data));
}
}));
decorateRequest
與intercept相反,decorateRequest選項(xiàng)用于在請(qǐng)求通過代理轉(zhuǎn)發(fā)至目標(biāo)主機(jī)之前陈醒,對(duì)請(qǐng)求進(jìn)行處理
app.use('/proxy', proxy('www.google.com', {
decorateRequest: function(proxyReq, originalReq) {
// you can update headers
proxyReq.headers['Content-Type'] = 'text/html';
// you can change the method
proxyReq.method = 'GET';
// you can munge the bodyContent.
proxyReq.bodyContent = proxyReq.bodyContent.replace(/losing/, 'winning!');
return proxyReq;
}
}));
https
通常代理請(qǐng)求的協(xié)議類型與原始請(qǐng)求保持一致惕橙,如果代理請(qǐng)求需要用https協(xié)議,可以用https選項(xiàng)強(qiáng)制實(shí)現(xiàn)
app.use('/proxy', proxy('www.google.com', {
https: true
}));
preserveHostHdr
可以用preserveHostHdr選項(xiàng)將HTTP頭部復(fù)制到express代理服務(wù)器的HTTP頭部
app.use('/proxy', proxy('www.google.com', {
preserveHostHdr: true
}));
reqAsBuffer
這是一個(gè)實(shí)驗(yàn)選項(xiàng)钉跷,用于在發(fā)送代理請(qǐng)求時(shí)弥鹦,保證請(qǐng)求體(req.body)編碼為Node Buffer
app.use('/proxy', proxy('www.google.com', {
reqAsBuffer: true
}));
reqBodyEncoding
request body默認(rèn)編碼格式為 utf-8。
當(dāng)代理請(qǐng)求體為Buffer時(shí)爷辙,使用null來保存緩沖(例如彬坏,圖像上傳) ,接受 raw-body支持的任何值膝晾。
編碼格式也可以通過intercept選項(xiàng)實(shí)現(xiàn)
app.use('/post', proxy('httpbin.org', {
reqBodyEncoding: null
}));
timeout
默認(rèn)情況下苍鲜。node在連接過程中,是沒有timeout的玷犹。使用timeout選項(xiàng)增加超時(shí)混滔,Timed-out requests 將會(huì)返回504和X-Timeout-Reason header。
app.use('/', proxy('httpbin.org', {
timeout: 2000 // in milliseconds, two seconds
}));