Node Express 4 middleware after routes

goofballLogic picture goofballLogic · Jun 17, 2014 · Viewed 33.8k times · Source

Following the upgrade to Express 4, and the removal of app.router, I'm struggling to get middleware to execute after routes execute.

e.g. the following code correctly responds with "hello", but never calls the configured middleware

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

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

    res.send( "hello" );

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

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

} );

express.listen( 8888 );

CLARIFICATION:

the following code shows "before" on the console, but not "after":

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

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

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

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

    res.send( "hello" );

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

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

} );

express.listen( 8888 );

Answer

Test picture Test · Aug 22, 2017

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();
});