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 );
Express. js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. Middleware gets executed after the server receives the request and before the controller actions send the response.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function.
The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects.
In closing, utilizing async / await as your Express middleware implementation helps keep your code reusable, readable, and up-to-date with current coding conventions.
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With