Node.js - Return res.status VS res.status
Node.js - Return res.status VS res.status
我很好奇返回响应和仅创建响应的区别。
我看过大量同时使用 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"})
正如@kasho 所解释的,这仅是短路功能所必需的。但是,我不建议 return 调用 send()
本身,而是在它之后。否则它会给出错误的表达式,即 send()
调用的 return 值很重要,但事实并非如此,因为它只是 undefined
.
if (!isAuthenticated) {
res.sendStatus(401)
return
}
res
.status(200)
.send(user)
我很好奇返回响应和仅创建响应的区别。
我看过大量同时使用 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"})
正如@kasho 所解释的,这仅是短路功能所必需的。但是,我不建议 return 调用 send()
本身,而是在它之后。否则它会给出错误的表达式,即 send()
调用的 return 值很重要,但事实并非如此,因为它只是 undefined
.
if (!isAuthenticated) {
res.sendStatus(401)
return
}
res
.status(200)
.send(user)