0

我有这样的代理配置:

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

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

我该如何配置?

4

1 回答 1

0

简单版:

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,
  },
}
于 2020-04-01T12:34:01.233 回答