提问者:小点点

app . get-RES . send和return res.send有什么区别吗


我是结点和快递新手,见过app.getapp.post例子同时使用“res.send”和“res.send”,这些是一样的吗?

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');
});

共3个答案

匿名用户

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");
});

匿名用户

我想指出它在我的代码中的确切位置。

我有一个对令牌进行身份验证的中间件。代码如下:

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();
  });
}

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

类似//标记2

如果在这些< code>if块中没有使用< code>return,请确保使用调用< code>next()的< code>else块。

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

匿名用户

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 :(');
});