我使用的是节点路由,我使用的是trycatch
块,但Node.js没有。当代码有错误时,它会转到Catch,它会失败。
try {
...
res.send({ message: 'All good nothing wrong with the code above' })
} catch {
res.status(500).send({ message: 'There is an error I want to send to the front end' })
}
Node显然对此不满意,我知道我无法发送res.send()
twice,但它位于trycatch
块上。如果出现故障,我如何向前端发送错误消息?
节点在CATCH块上抱怨:
'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client'
更新
我修复了这个问题,方法是将错误对象WITH发送到CATCH块,并且不对除一次以外的任何条件使用TRY CATCH上的res.send()
2条答案
按热度按时间3qpi33ja1#
当您想要发送一些东西而不做其他任何事情时,终止函数的执行流总是很好的。
ndasle7k2#
您不能使用两次
res.send
,因此请添加return
。