美文网首页
使用express-http-proxy中的proxy,需要注意

使用express-http-proxy中的proxy,需要注意

作者: 提莫小小队长 | 来源:发表于2022-04-07 17:28 被阅读0次

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

    # 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,需要注意

          本文链接:https://www.haomeiwen.com/subject/xkdssrtx.html