【问题标题】:Proxy request to local file对本地文件的代理请求
【发布时间】:2020-07-13 00:29:27
【问题描述】:

我有这样的代理配置:

proxy: {
  "/api/smth": {
    target: "http://api.example.com/",
    secure: false,
    changeOrigin: true,
  },
}

现在我想将 api 调用 /api/*/meta 重定向到本地文件 %PROJ_ROOT%/meta/*.json

我该如何配置?

【问题讨论】:

    标签: webpack proxy webpack-dev-server http-proxy-middleware


    【解决方案1】:

    简单版:

    proxy: {
      "/api/*/meta": {
        selfHandleResponse: true,
        bypass(req, resp) {
          const id = req.url.match(/api\/([-\w]+)\/meta/)[1];
          resp.header("Content-Type", "application/json");
          fs.createReadStream(`./meta/${id}.json`).pipe(resp);
        },
      },
      "/api/smth": {
        target: "http://api.example.com/",
        secure: false,
        changeOrigin: true,
      },
    }
    

    带有状态码的版本:

    proxy: {
      "/api/*/meta": {
        selfHandleResponse: true,
        bypass(req, resp) {
          const id = req.url.match(/api\/([-\w]+)\/meta/)[1];
          const jsonStream = fs.createReadStream(`./meta/${id}.json`);
    
          jsonStream.on("open", () => {
            resp.header("Content-Type", "application/json");
            jsonStream.pipe(resp);
          });
    
          jsonStream.on("error", err => {
            resp.status(err.code === 'ENOENT' ? 404 : 500);
            resp.send(err);
          });
        },
      },
      "/api/smth": {
        target: "http://api.example.com/",
        secure: false,
        changeOrigin: true,
      },
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-07
      • 2017-09-15
      • 2018-10-05
      • 2012-02-08
      • 2019-04-04
      • 2015-01-05
      相关资源
      最近更新 更多