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

标签 node.js http express response

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

我见过大量使用 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/

相关文章:

node.js - Node和Google App Engine的CORS问题(等级)

java - 从 Java Android 填写表单并发送请求

http - 从另一台 PC 向在本地主机上运行的 API 服务器发送 HTTP POST

http - 'GoogleHttpClient.send'('Future<StreamedResponse> Function(BaseRequest)')不是 'IOClient.send'的有效替代

node.js - 在 meteor 中使用 NPM 安装 bcrypt 时出错

multithreading - 为什么 Node 空闲时有两个线程?

sockets - 多个node.js进程之间的通信

mysql - SpringBoot-MySQL 或 ExpressJS-MongoDB 哪一个最适合构建在线书店的 REST API?

node.js - 无法读取未定义 Mongoose 的属性 'length'

node.js - 从 ytdl-core express 下载的 360p 以上视频没有音频?