Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Express 4 middleware after routes

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 ); 
like image 425
goofballLogic Avatar asked Jun 17 '14 08:06

goofballLogic


People also ask

Which middleware is used to handle the routing logic in Express?

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.

What should you call at the end of your middleware function?

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function.

What is next in middleware Express?

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.

Can Express middleware be async?

In closing, utilizing async / await as your Express middleware implementation helps keep your code reusable, readable, and up-to-date with current coding conventions.


1 Answers

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(); }); 
like image 183
Test Avatar answered Oct 11 '22 15:10

Test