【发布时间】:2021-08-11 13:23:15
【问题描述】:
我正在尝试使用 express 和 http-proxy-middleware@2.0.1 创建一个带有一些内置验证的反向代理。希望在 onProxyReq 函数中,我可以进行检查,如果失败,我会将错误返回给调用者,而不是继续代理请求。
似乎如果我立即发送带有“无效”的 404,那么它会按预期工作。如果在执行验证操作时有任何延迟(这里用 setTimeout() 模拟),那么它会抛出错误“在将标头发送到客户端后无法设置标头”。有没有办法让 onProxyReq “等待”直到我的验证完成,我可以决定是否需要以错误响应客户端,或者继续使用代理。
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
function onProxyReq(proxyReq, req, res) {
// Some validation
// ** This causes the error "Cannot set headers after they are sent to the client"
// setTimeout(()=>{
// res.status(404).send('Invalid')
// }, 500)
// ** This returns "Invalid" to the client as expected
return res.status(404).send('Invalid')
}
// proxy middleware options
const options = {
target: 'https://google.com',
changeOrigin: true,
logLevel: 'debug',
onProxyReq,
};
const testProxy = createProxyMiddleware(options);
const app = express();
app.use('/', testProxy);
app.listen(3000);
【问题讨论】:
标签: node.js http-proxy-middleware