【问题标题】:Node.js - Return res.status VS res.statusNode.js - 返回 res.status VS res.status
【发布时间】:2021-08-11 06:10:16
【问题描述】:

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

我见过大量同时使用return res.status(xxx).json(x)res.status(xxx).json(x) 的代码示例。

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

【问题讨论】:

    标签: node.js http express response


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      if (!isAuthenticated) {
        res.sendStatus(401)
        return
      }
      
      res
        .status(200)
        .send(user)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 2021-03-14
        • 2019-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多