exit from chain of route specific middleware in express/ nodejs

前端 未结 3 1427
清歌不尽
清歌不尽 2021-02-08 05:07

I have a chain of \"route specific middleware\" for this route, like so:

    var express = require(\'express\');
    var server = express();
    var mw1 = functi         


        
3条回答
  •  面向向阳花
    2021-02-08 06:10

    I was under the impression that if you neither call next() nor send a response in a route handling function, express just hangs. Also FWIW I haven't used an array, mine looks like server.post('/some/path', mw1, mw2, function(req, resp) {...

    Anyway. One alternative might be to restructure your code so you only have a single handling function. Do you have a good reason for mw1 and mw2 being middleware instead of regular async functions your handler calls?

    var express = require('express');
    var server = express();
    
    var mw1 = function(req, res, callback) {
      // do stuff with req/res if necessary but don't send a response
      if (success) {
        callback(null);
      } else {
        callback('Error');
      }
    };
    
    var mw2 = function(req, res, callback) {
      //do other stuff but don't send a response
      if (success) {
        callback(null);
      } else {
        callback('Error');
      }
    };
    
    function mwBoth(req, res){
      mw1(req, res, function(err){
        if(err){ return res.send(500) };
        mw2(req, res, function(err){
          if(err){ return res.send(500) };
          // neither had an error
          res.redirect('/some/other/path');
        });
      });
    };
    
    server.post('/some/path', mwBoth);
    

提交回复
热议问题