我正在使用http- proxy -middleware (https://github.com/chimurai/http-proxy-middleware#http-proxy-events)实现到另一个REST API (称为/rest-api)的简单代理(称为my-proxy/),该代理要求用户在HTTP header auth-token中传递一个身份验证令牌。可以使用正文中的凭证从端点POST /rest-api/auth获取令牌。
我希望我的代理接收传入的请求,并检查是否在请求标头中设置了auth-token,如果没有,则在将请求传递给rest-api/之前执行POST /rest-api/auth以检索令牌并在标头中设置auth-token。
在代理配置中,我指定
onProxyReq: function (proxyReq, req, res) {
if (!req.header("auth-token")) {
const authRequest = request({
url: 'rest-api/auth',
method: 'POST',
json: {"username": "user", "password": "pass"}
},
function (error, resp, body) {
proxyReq.setHeader("auth-token", body.token)
}
);
}
}我可以看到body.token返回正确的令牌。但是,由于Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client,setHeader调用失败。
我认为这意味着我修改的请求在等待回调之前已经被发送到rest-api/,但我不知道在我的场景中如何最好地解决这个问题。
有什么帮助吗?
发布于 2019-12-31 12:09:04
我今天遇到了同样的问题。我通过使用一个单独的中间件(在http代理之前)来解决这个问题。
伪码
// fix token stuff here in a separate middleware
app.use('/api', async (req, res, next) => {
if (!req.session.token) {
const resToken = await axios.post(token_url, data, options)
req.session.token = resToken.data
}
next()
}
// proxy middleware options
const proxyOptions = {
target: config.gateway.url, // target host
changeOrigin: true,
pathRewrite: function(path, req) {
return path.replace('/api', '')
},
onProxyReq: function onProxyReq(proxyReq, req, res) {
// add custom header to request
let token = req.session.token
if (token) {
proxyReq.setHeader('Authorization', `bearer ${token.access_token}`)
}
},
logLevel: 'debug',
}
app.use(proxy('/api', proxyOptions))希望这能有所帮助!
https://stackoverflow.com/questions/57271080
复制相似问题