In Express, what does app.router do exactly?


When I create a sample Express application using the express binary, the bootstrap code has these lines:


var app = express();

I didn't find much about app.router. I thought that this is the middleware that handles the routing (app.get(), etc.) rules, but these rules also get executed when I remove the app.use(app.router); line.

So what is the exact purpuse of this middleware?

11/6/2012 3:48:25 PM

Accepted Answer

This is from the Express 2.x guide

"Note the use of app.router, which can (optionally) be used to mount the application routes, otherwise the first call to app.get(),, etc will mount the routes."

I suspect this applies to Express 3.x too.

11/6/2012 4:29:54 PM

In Express 3.x, app.router is an enhanced version of the connect middleware router. As hector said, this is were Express handles the request handlers registered with app.get,, etc.

If you do not call app.use(app.router) explicitly then express will call it implicitly the first time you use app.get(...),, etc. However, you may want to .use it explicitly, because then you choose the the order of all your middleware.

// app.get,, etc called before static folder
app.use(express.static(path.join(__dirname, 'public')));

See how the router is retrieved in the Express 3 source here.

Note that Express 4 doesn't need app.router.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow