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