使用express-http-proxy中的proxy,需要注意url带path的情况

之前项目代码里有一段这样的代码

# A文件
const resp = await fetch('/resourceUrl/resImage/replace', {
  method: 'POST',
  body: formData,
});
# server.js
app.use(
  '/resourceUrl',
  proxy(resourceUrl, {
    limit: '100mb',
    timeout: 3 * 60 * 1000, // 3min
    proxyReqOptDecorator(proxyReqOpts, srcReq) {
      const opts = proxyReqOpts;
      // you can update headers
      opts.headers.Authorization =
        (srcReq.session.user && srcReq.session.user.accessToken) || '';
      // you can change the method
      // opts.method = 'GET';
      return opts;
    },
  }),
);

之前我的resourceUrl是 https://www.xxx.com 这种地址,所以一直用着都没什么问题,但是今天我换成了https://www.xxx.com/aaa/bbb 这样带路径的,就会出现问题

fetch请求的地址转发成了下面的请求,丢失了/aaa/bbb这段路径

 https://www.xxx.com/resImage/replace

所以我们需要对proxy加个参数

app.use(
  '/resourceUrl',
  timeout('180s'),
  proxy(resourceUrl, {
    limit: '100mb',
    timeout: 3 * 60 * 1000, // 3min
    proxyReqPathResolver: req => resourceUrl + req.url,
    proxyReqOptDecorator(proxyReqOpts, srcReq) {
      const opts = proxyReqOpts;
      // you can update headers
      opts.headers.Authorization =
        (srcReq.session.user && srcReq.session.user.accessToken) || '';
      // you can change the method
      // opts.method = 'GET';
      return opts;
    },
  }),
);

加一个proxyReqPathResolver拼一下路径就好了, 带query的地址同理

文档地址
https://github.com/villadora/express-http-proxy

你可能感兴趣的:(使用express-http-proxy中的proxy,需要注意url带path的情况)