我有这样的代理配置:
proxy: {
"/api/smth": {
target: "http://api.example.com/",
secure: false,
changeOrigin: true,
},
}现在我想将接口调用/api/*/meta重定向到本地文件%PROJ_ROOT%/meta/*.json。
我该如何配置它?
发布于 2020-04-01 20:34:01
简单版本:
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,
},
}https://stackoverflow.com/questions/60967796
复制相似问题