express-http-proxy使用

官方文檔

使用說(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/*`上
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容