28

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

...

var app = express();
...
app.use(app.router);

I didn't find much about app.router. I thought that this is the middleware that handles the routing (app.get(), app.post() 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?

Zsombor Erdődy-Nagy
  • 16,864
  • 16
  • 76
  • 101
  • 1
    If you don't explicitly define it express will do it for you when it encounters app.verb. – Pickels Nov 06 '12 at 17:48
  • Nice answer here http://stackoverflow.com/questions/12695591/node-js-express-js-how-does-app-router-work – IvanM May 07 '13 at 05:54
  • 2
    as of express 4, app.use(app.router) is removed. please see the docs https://github.com/visionmedia/express/wiki/New-features-in-4.x – Jonathan Ong Mar 05 '14 at 06:59

4 Answers4

38

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

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

app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
// app.get, app.post, etc called before static folder
app.use(app.router); 
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.

Charles Holbrow
  • 3,967
  • 6
  • 30
  • 35
  • 5
    I understand why @Zsombor accepted the other answer, which was the only one near the time of his asking, but this answer is much better in that it highlights the primary reason you would want to call app.router explicitly, which is to control the order installation. – T Nguyen Jul 26 '13 at 13:23
17

This is from the Express 2.x guide http://expressjs.com/2x/guide.html

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

I suspect this applies to Express 3.x too.

Hector Correa
  • 26,290
  • 8
  • 57
  • 73
5

In my case i wasn't exporting the module

module.exports = router;
Usama Tahir
  • 1,235
  • 12
  • 14
0

This method has been deprecated

why we use router ..because of we need to connect our sub app to our main app.

Nitin .
  • 808
  • 9
  • 12