After sending response, how to end the current request processing in Node/Express?

后端 未结 1 640
-上瘾入骨i
-上瘾入骨i 2021-01-04 22:51

There are a few posts on this question but none that answers the issue directly, head-on. Let me clarify that I understand (or so I think) the use of next(), next(\'route\')

相关标签:
1条回答
  • 2021-01-04 23:57

    According to the express documentation on http://expressjs.com/guide/using-middleware.html

    If the current middleware does not end the request-response cycle,
    it must call next() to pass control to the next middleware,
    otherwise the request will be left hanging.
    

    so if a middleware needs to end the request-response early, simply do not call next() but make sure that the middleware really ends the request-response by calling res.end, res.send, res.render or any method that implicitely calls res.end

    app.use(function (req, res, next) {
      if (/* stop here */) {
        res.end();
      } else {
        next();
      }
    });
    

    Here is an example server showing that it works

    var express = require('express');
    var app = express();
    
    var count = 0;
    app.use(function(req, res, next) { 
      console.log('f1'); 
      next();
     })
    app.use(function(req, res, next) {
      console.log('f2');
      if (count > 1) {
        res.send('Bye');
      } else {
        next();
      }
    })
    app.use(function(req, res, next) {
      console.log('f3');
      count++;
      next();
    })
    
    app.get('/', function (req, res) {
      res.send('Hello World: ' + count);
    });
    
    var server = app.listen(3000);
    

    you will see the after 3 requests, the server shows "Bye" and f3 is not reached

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