Node.js - 返回 res.status VS res.status

Jon*_*sen 4 http response node.js express

我很好奇返回响应和仅创建响应的区别。

我已经看到了大量使用return res.status(xxx).json(x)和的代码示例res.status(xxx).json(x)

有没有人能够详细说明两者之间的区别?

adi*_*ius 11

正如 @kasho 所解释的,这只是短路函数所必需的。但是,我不建议返回send()呼叫本身,而是在呼叫之后返回。否则它会给出错误的表达式,即调用的返回值send()很重要,但事实并非如此,因为它只是undefined.

if (!isAuthenticated) {
  res.sendStatus(401)
  return
}

res
  .status(200)
  .send(user)
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您有条件并且想提前退出,您可以使用 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"})
Run Code Online (Sandbox Code Playgroud)