How to have a NodeJS/connect middleware execute after responde.end() has been invoked?

前端 未结 3 2035
清歌不尽
清歌不尽 2020-12-29 10:27

I would like to achieve something like this:

var c = require(\'connect\');
var app = c();

app.use(\"/api\", function(req, res, next){
    console.log(\"requ         


        
3条回答
  •  温柔的废话
    2020-12-29 10:49

    What a great question to try work out with your morning coffee!

    So looking through proto.js, if you have a look down to line 102 which is app.handle which is the handler code for the middleware stack, you'll see how next() operates.

    Where the function next() is called, you can see it checks if res.headerSent is true and if so it throws an error.

    If modify line 14 to:

    app.use("/api", function(req, res, next){
       console.log("request handler");
        res.end("hello");
        console.log(res);
        next();
    });
    

    You will see that it actually sets "headersSent" to true. So after we've ended the request, you can see from the next() code that it throws the error because of the conditions discussed.

提交回复
热议问题