【问题标题】:app.get - is there any difference between res.send vs return res.sendapp.get - res.send 与 return res.send 之间有什么区别吗
【发布时间】:2017-08-20 16:52:48
【问题描述】:

我是 node 和 express 的新手。我已经看到了使用“res.send”和“return res.send”的 app.get 和 app.post 示例。这些是一样的吗?

var express = require('express');
var app = express();

app.get('/', function(req, res) {
  res.type('text/plain');
  res.send('i am a beautiful butterfly');
});

var express = require('express');
var app = express();

app.get('/', function(req, res) {
  res.type('text/plain');
  return res.send('i am a beautiful butterfly');
});

【问题讨论】:

标签: node.js express


【解决方案1】:

return 关键字从您的函数返回,从而结束其执行。这意味着它之后的任何代码行都不会被执行。

在某些情况下,您可能想使用res.send,然后做其他事情。

app.get('/', function(req, res) {
  res.send('i am a beautiful butterfly');
  console.log("this gets executed");
});

app.get('/', function(req, res) {
  return res.send('i am a beautiful butterfly');
  console.log("this does NOT get executed");
});

【讨论】:

  • 是的!我用例子来解释。
【解决方案2】:
app.get('/', function(req, res) {
    res.type('text/plain');
    if (someTruthyConditinal) {
        return res.send(':)');
    }
    // The execution will never get here
    console.log('Some error might be happening :(');
});

app.get('/', function(req, res) {
    res.type('text/plain');
    if (someTruthyConditinal) {
        res.send(':)');
    }
    // The execution will get here
    console.log('Some error might be happening :(');
});

【讨论】:

    【解决方案3】:

    我想指出它对我的代码的影响。

    我有一个验证令牌的中间件。代码如下:

    function authenticateToken(req, res, next) {
      const authHeader = req.headers['authorization'];
      const token = authHeader && authHeader.split(' ')[1] || null;
    
      if(token === null) return res.sendStatus(401); // MARKED 1
      jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
        if(err) return res.sendStatus(403); // MARKED 2
        req.user = user;
        next();
      });
    }
    

    // MARKED 1 行上,如果我没有写return,中间件将继续调用next() 并发送状态为200 的响应,而不是预期的行为。

    // MARKED 2 也一样

    如果您不在这些 if 块内使用 return,请确保您使用的是调用 next()else 块。

    希望这有助于理解这个概念并从一开始就避免错误。

    【讨论】:

      猜你喜欢
      • 2015-06-15
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      相关资源
      最近更新 更多