express-http-proxy使用

官方文档

使用说明

proxy(host, options);

host 参数选项

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参数选项

const httpProxy = require('express-http-proxy')
const app = express();

const userServiceProxy = httpProxy('http://google.com', {
  //过滤器,指定类型的转发(可选)
  filter: function (req, res) {
    return req.method == 'GET';
  },
  //请求路径解析,转换一下路径(可选)
  proxyReqPathResolver: function (req) {
    var parts = req.url.split('?');
    var queryString = parts[1];
    var updatedPath = parts[0].replace(/test/, 'tent');
    return updatedPath + (queryString ? '?' + queryString : '');
  },
  //处理响应(可选)
  userResDecorator: function (proxyRes, proxyResData, userReq, userRes) {
    data = JSON.parse(proxyResData.toString('utf8'));
    data.newProperty = 'exciting data';
    return JSON.stringify(data);
  },
  //处理请求(可选)
  proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
    // you can update headers
    // proxyReqOpts.headers['Content-Type'] = 'text/html';
    // you can change the method
    // proxyReqOpts.method = 'GET';
    return proxyReqOpts;
  },
  //处理请求body(可选)
  proxyReqBodyDecorator: function (bodyContent, srcReq) {
    console.log(bodyContent);
    return bodyContent;
  },
  //处理请求头(可选)
  userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) {
    // recieves an Object of headers, returns an Object of headers.
    return headers;
  },
  //自定义错误(可选)
  proxyErrorHandler: function (err, res, next) {
    next(err);
  }
})
  
认证、限速等一系列中间件
app.use((req, res, next) => {
  next()
})

// 代理请求
app.get('/test/*', (req, res, next) => {
  userServiceProxy(req, res, next)
})

`http://localhost:3000/test/*` 代理到 `http://google.com/tent/*`上

你可能感兴趣的:(express-http-proxy使用)