app.get - is there any difference between res.send vs return res.send

后端 未结 3 463
误落风尘
误落风尘 2020-12-25 09:42

I am new to node and express. I have seen app.get and app.post examples using both \"res.send\" and \"return res.send\". Are these the same?

var express = r         


        
相关标签:
3条回答
  • 2020-12-25 10:28

    The return keyword returns from your function, thus ending its execution. This means that any lines of code after it will not be executed.

    In some circumstances, you may want to use res.send and then do other stuff.

    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");
    });
    
    0 讨论(0)
  • 2020-12-25 10:30
    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 :(');
    });
    
    0 讨论(0)
  • 2020-12-25 10:42

    I would like to point out where it exactly made a difference in my code.

    I have a middleware which authenticates a token. The code is as follows:

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

    On the // MARKED 1 line, if I did not write return, the middleware would proceed and call next() and send out a response with status of 200 instead which was not the intended behaviour.

    The same goes for like // MARKED 2

    If you do not use return inside those if blocks, make sure you are using the else block where next() gets called.

    Hope this helps in understanding the concept and avoiding bugs right from the beginning.

    0 讨论(0)
提交回复
热议问题