我很好奇返回响应和仅创建响应的区别。
我见过大量使用 return res.status(xxx).json(x)
的代码示例和res.status(xxx).json(x)
.
谁能详细解释一下两者的区别吗?
最佳答案
如果你有条件并且想提前退出,你可以使用 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"})
关于Node.js - 返回 res.status VS res.status,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52919585/