我很好奇返回一个回复和仅仅创建一个回复之间的区别。
我看到了大量使用return res.status(xxx).json(x)和res.status(xxx).json(x)的代码示例。
有人能详细说明两者之间的区别吗?
发布于 2018-10-21 21:01:10
如果您有一个条件,并且希望尽早退出,您将使用return,因为多次调用res.send()将引发一个错误。例如:
//...Fetch a post from db
if(!post){
// Will return response and not run the rest of the code after next line
return res.status(404).send({message: "Could not find post."})
}
//...Do some work (ie. update post)
// Return response
res.status(200).send({message: "Updated post successfuly"})发布于 2021-06-09 18:47:26
正如@kasho所解释的那样,这仅是短路功能所必需的。但是,我不建议返回send()调用本身,而是在它之后返回。否则,它会给出错误的表达式,认为send()调用的返回值很重要,但它并不重要,因为它只是undefined。
if (!isAuthenticated) {
res.sendStatus(401)
return
}
res
.status(200)
.send(user)https://stackoverflow.com/questions/52919585
复制相似问题