需要帮助处理一些奇怪的错误
这是托管在heroku上的速递nodejs服务。
这是我的路线控制器代码
async function PopupConroller(req, res) {
let credential = req.credential;
let zoho_token = null;
console.log('res :>> ', res);
try {
zoho_token = await axios.post(`https://accounts.zoho.com/oauth/v2/token?client_id=${credential.client_id}&client_secret=${credential.client_secret}&refresh_token=${credential.refresh_token}&grant_type=refresh_token`);
console.log('zoho_token.data :>> ', zoho_token.data);
} catch (error) {
console.log('ex 2 :>> ',error);
}
console.log('res :>> ', res);
res.status(200).json({status:"ok"});
return;}
当服务接收到请求时,代码抛出此错误(没有来自axios.post请求的错误)
回复: 200,OK,没有人
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:530:11)
at ServerResponse.header (/app/node_modules/express/lib/response.js:771:10)
at ServerResponse.json (/app/node_modules/express/lib/response.js:264:10)
at PopupConroller (/app/voicenter.js:261:28)
at processTicksAndRejections (internal/process/task_queues.js:97:5)删除这些行时,所有内容都是ok响应: 200 OK和{status:"ok"}
async function PopupConroller(req, res) {
let credential = req.credential;
let zoho_token = null;
console.log('res1 :>> ', res);
try {
//zoho_token = await axios.post(`https://accounts.zoho.com/oauth/v2/token?client_id=${credential.client_id}&client_secret=${credential.client_secret}&refresh_token=${credential.refresh_token}&grant_type=refresh_token`);
//console.log('zoho_token.data :>> ', zoho_token.data);
} catch (error) {
console.log('ex 2 :>> ',error);
}
console.log('res2 :>> ', res);
res.status(200).json({status:"ok"});
return;}
在第一个例子中,
当我检查res对象(console.log res1)时,没有发送标头,但是在第二个(console.log res2)中,我注意到响应头被发送回来了。
这一行发送标头的方式?*需要说,在其他路由中,类似的代码可以很好地执行。
zoho_token = await axios.post(`https://accounts.zoho.com/oauth/v2/token?client_id=${credential.client_id}&client_secret=${credential.client_secret}&refresh_token=${credential.refresh_token}&grant_type=refresh_token`);感谢你的帮助..。谢谢
发布于 2020-12-03 20:56:47
我猜这就是你想要的吗?
为了扩展下面的代码片段,您将得到错误cannot set headers after they are sent to the client,因为axios.post()使成为 HTTP请求。
在您的代码中,您通过axios进行HTTP调用,从而将头发送出去。
之后,JS解析器继续对代码进行计算,在try块之后,由于没有错误,它对已经发送的响应计算res.status(),因此出现错误。
因此,要解决这个问题,您可以像处理一样处理post请求,而不需要再次将响应重发到客户端。然后,您可以在‘thenable’函数中使用允诺响应“做一些事情”。
如果您想通过axios发布一个可选对象,可以通过将参数传递到post请求来实现。
async function PopupConroller(req, res) {
let credential = req.credential;
let zoho_token = await axios.post("whatever", {"cat": "meaows"})
.then((response)=> {
// do something with the response
})
.catch((err) => console.log(err))
}https://stackoverflow.com/questions/65133854
复制相似问题