exit from chain of route specific middleware in express/ nodejs

前端 未结 3 1415
清歌不尽
清歌不尽 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 05:54

    A little more tinkering yielded the answer:

    var express = require('express');
    var server = express();
    var mw1 = function(req, resp, next) {
      //do stuff
      if (success) {
        next();
      } else {
        resp.send(406, 'Invalid because of this');
        req.connection.destroy(); //without calling next()
      }
    };
    var mw2 = function(req, resp, next) {
      //do stuff
      if (success) {
        next();
      } else {
        resp.send(406, 'Invalid because of that');
        req.connection.destroy(); //without calling next()
      }
    };
    server.post('/some/path', [mw1, mw2], function(req, resp) {
      //write response
    });
    

    The trick was send a response: resp.send(406, 'Invalid because of this');

    Just prior to destroying the connection: req.connection.destroy();

    In fact not destroying the connection, I found to also work, in the general case.

    (But was required in my specific case, and is out of the scope of this question.)

    If the response has already been sent, then express does not automatically call next() for you, as it appeared to do otherwise.

提交回复
热议问题