Node Express 4 middleware after routes

坚强是说给别人听的谎言 提交于 2019-12-03 22:07:23

In regards to Express 4, the "after" function from your second example never gets called because the middle function never calls next().

If you want the "after" function to get called, then you need to add and call the next callback from your middle function like this:

var express = require( "express" )();

express.use( function( req, res, next ) {

  console.log( "before" );
  next();

} );
express.get( "/", function( req, res, next ) {

  res.send( "hello" );
  next();      // <=== call next for following middleware 

} );
express.use( function( req, res, next ) {

  console.log( "after" );
  next();

} );

express.listen( 8888 );

res.send() writes the headers and response back to the client.

Beware, that once res.send() has been called, you won't want to update your response headers or contents. But you can do other tasks like database updates or logging.

Note that express looks at the the number of arguments in the middleware function and does different logic. Take express error handlers for example, which have 4 parameters defined.

express error handler signature: app.use(function(err, req, res, next) {});

Calling next on the very last item in your middleware chain is optional, but probably a good idea in case you ever change things around.

Test

The correct answer is using the res.on("finish", cb) callback.

i.e.:

express.use(function(req, res, next) {
    console.log("before");

    res.on("finish", function() {
        console.log("after");
    });

    next();
});

Have you checked putting your console.log after the next() call?

express.use( function( req, res, next ) {
  next();
  console.log( "world" );
});
express.get( "/", function( req, res ) {
  res.send( "hello" );
});

Order is important http://expressjs.com/4x/api.html#app.use

express.use( function( req, res, next ) {
  console.log( "world" );
  next();
});
express.get( "/", function( req, res ) {
  res.send( "hello" );
});

you can use the Middle ware function in different js file and you can use require function. so that it will be called before and after the http request.

    index.js:     
        const logger = require("./logger");    
           const express = require("express");    
           var app = express();    
           app.listen("3000",()=>console.log("listening on 3000..."))    
        app.use(logger("AppServer"));    
        //get expression    
        app.get("/", function(req,res){    
           console.log("res not received");    
            res.send("Hello World");    
           console.log("res received");    
        })   

    logger.js   

    module.exports = (applicationName) =>{
        return function log(req,res,next){
       console.log(applicationName+" started "+os.hostname);
        res.on("finish",()=>{
            console.log(applicationName+" completed "+os.hostname);
        })
        next();
        }};

output:   
AppServer started hostname-PC   
res not received   
res received   
AppServer completed hostname-PC 

Note: in the logger.js instead of using res.on("finish",callback), you can use req.on("end",callback)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!