Express / node.js 发送后无法设置 headers
Express / node.js Can't set headers after they are sent
我正在尝试通过服务器传送我的 session api 请求,以便设置带有 session 令牌的 httpOnly cookie,并且 运行 进入错误提示:
Can't set headers after they are sent
不完全确定这是什么意思,但这是我的 express 拦截器,它侦听 post 到 /api/sessions
端点,并在成功的情况下设置一个 cookie
app.post('/api/sessions', (req, res) => {
const url = `${config.API_HOST}/sessions`
let apiCall = request.post(url, (err, response, body) => {
if (!err && response.statusCode === 200) {
const data = JSON.parse(body)
let sessionCookie = {
path: '/',
hostOnly: true,
secure: true,
httpOnly: true
}
res.cookie('SESS', data.token, sessionCookie)
}
})
req.pipe(apiCall).pipe(res)
})
编辑:我通过管道传输它的原因是能够在我的客户端应用程序中使用承诺。
从上面的错误消息来看,您正试图在代码中的某个位置发送两次响应。 Can't set headers after they are sent
表示您的代码正在尝试在发送先前的响应后修改响应 headers(可能是为了发送新的响应)。
根据您的实施,您在 res.cookie('SESS', data.token, sessionCookie)
中调用 res
在 apiCall
定义中,并且还在这一行 apiCall
中将 res
传递给 res
req.pipe(apiCall).pipe(res)
,第二次修改响应 object。我认为 res.cookie
在内部调用 res.end
。如果是这种情况,任何进一步调用或编辑 res
都会抛出您遇到的错误。
您应该可以通过删除 req.pipe(apiCall).pipe(res)
中的 .pipe(res)
部分来解决这个问题,只需使用
req.pipe(apiCall)
您可以查看 this question on how to set and send cookies in express and this question 以更好地解释错误消息。
我正在尝试通过服务器传送我的 session api 请求,以便设置带有 session 令牌的 httpOnly cookie,并且 运行 进入错误提示:
Can't set headers after they are sent
不完全确定这是什么意思,但这是我的 express 拦截器,它侦听 post 到 /api/sessions
端点,并在成功的情况下设置一个 cookie
app.post('/api/sessions', (req, res) => {
const url = `${config.API_HOST}/sessions`
let apiCall = request.post(url, (err, response, body) => {
if (!err && response.statusCode === 200) {
const data = JSON.parse(body)
let sessionCookie = {
path: '/',
hostOnly: true,
secure: true,
httpOnly: true
}
res.cookie('SESS', data.token, sessionCookie)
}
})
req.pipe(apiCall).pipe(res)
})
编辑:我通过管道传输它的原因是能够在我的客户端应用程序中使用承诺。
从上面的错误消息来看,您正试图在代码中的某个位置发送两次响应。 Can't set headers after they are sent
表示您的代码正在尝试在发送先前的响应后修改响应 headers(可能是为了发送新的响应)。
根据您的实施,您在 res.cookie('SESS', data.token, sessionCookie)
中调用 res
在 apiCall
定义中,并且还在这一行 apiCall
中将 res
传递给 res
req.pipe(apiCall).pipe(res)
,第二次修改响应 object。我认为 res.cookie
在内部调用 res.end
。如果是这种情况,任何进一步调用或编辑 res
都会抛出您遇到的错误。
您应该可以通过删除 req.pipe(apiCall).pipe(res)
中的 .pipe(res)
部分来解决这个问题,只需使用
req.pipe(apiCall)
您可以查看 this question on how to set and send cookies in express and this question 以更好地解释错误消息。