代理请求到本地文件
Proxy request to local file
我有这样的代理配置:
proxy: {
"/api/smth": {
target: "http://api.example.com/",
secure: false,
changeOrigin: true,
},
}
现在我想将 api 调用 /api/*/meta
重定向到本地文件 %PROJ_ROOT%/meta/*.json
。
我该如何配置?
简单版:
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,
},
}
我有这样的代理配置:
proxy: {
"/api/smth": {
target: "http://api.example.com/",
secure: false,
changeOrigin: true,
},
}
现在我想将 api 调用 /api/*/meta
重定向到本地文件 %PROJ_ROOT%/meta/*.json
。
我该如何配置?
简单版:
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,
},
}