【问题标题】:In Express.js why does code after res.json() still execute?在 Express.js 中为什么 res.json() 之后的代码仍然执行?
【发布时间】:2016-09-15 19:47:38
【问题描述】:

在 Node with Express 中,我有一段这样的代码。

 if (req.body.var1 >= req.body.var2){
        res.json({success: false, message: "End time must be AFTER start time"});
        console.log('Hi')
 }
 console.log('Hi2')
 //other codes

我预计如果 var1 >= var2,则会发送响应并结束执行。类似于 Java/C# 中的 return 语句

但显然情况并非如此。发送响应后,“Hi”和“Hi2”以及之后的所有其他代码都会继续执行。

我想知道如何阻止这种情况发生?

另外,我想知道在什么情况下您实际上希望代码在响应已发送后继续执行。

干杯

【问题讨论】:

    标签: javascript json node.js express httpresponse


    【解决方案1】:

    Express 只是为匹配的路由调用一个 JavaScript 函数。知道函数何时完成/不完整没有什么特别的方法。它只是运行该功能。但是,随时退出该功能非常容易...

    您可以使用return 停止执行快递中特定路由的回调。它只是 JavaScript ......该函数将始终尝试运行完成

    app.post('/some/route', (req, res)=> {
      if (req.body.var1 >= req.body.var2){
        // note the use of `return` here
        return res.json({success: false, message: "End time must be AFTER start time"});
        // this line will never get called
        console.log('Hi')
      }
      // this code will only happen if the condition above is false
      console.log('Hi2')
      //other codes
    });
    

    关于字符串比较的警告

    你正在使用

    req.body.var1 >= req.body.var2
    

    所有 HTML 表单值都作为字符串发送到服务器。

    // javascript string comparison
    "4" > "3"  //=> true
    "4" > "30" //=> true
    parseInt("4", 10) > parseInt("30", 10) //=> false
    

    我敢肯定,您需要进行比这更有根据的比较。看起来它们是时间值?因此,您可能希望将这些值转换为 Date 对象并进行准确的比较。

    【讨论】:

    • 是的,它们是秒的整数值。谢谢你的提醒!我想我需要像你一样解析它们?我不知道所有内容都是作为字符串发送的。这可能让我很头疼。非常感谢。
    【解决方案2】:

    res.json函数之后直接返回:

    res.json({success: false, message: "End time must be AFTER start time"});
    return; // This will stop anything else from being run
    

    【讨论】:

      【解决方案3】:

      您也可以返回res.json

      if (req.body.var1 >= req.body.var2){
      return res.status(400).json({success: false, message: 'your message'})
      }
      

      【讨论】:

        猜你喜欢
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-03
        • 1970-01-01
        • 2020-09-09
        • 1970-01-01
        • 2012-05-26
        相关资源
        最近更新 更多