2

in the default app.js generated by express.js, there is a following line:

...
app.use(app.router);
... 

I am confused by this line of code, because 1) I couldn't find app has a property with the name "router" on express api doc. 2) "app.router" is not mentioned/defined in the code.

There is a one property called "app.routes". it is not the same thing, right?

Please help me explain what is app.router and where it comes from. Thank you!

Daniel F. Thornton
  • 3,687
  • 2
  • 28
  • 41
Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129

1 Answers1

4

app.router is the routing middleware of Express. In other words, it's the middleware that is used to process incoming requests and match them to any routes that you may have set up.

Even though the default app adds it, it's not required because Express will automatically add the routing middleware when you first declare a route.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • right above the app.use(app.router) line of code, I added "console.log(app.router)". The output is "undefined". So it doesn't exist. Is this right? – Nicolas S.Xu Nov 24 '13 at 02:10
  • @NicolasS.Xu no, that doesn't sound right. Can you post some more code? – robertklep Nov 24 '13 at 06:46
  • Here is result I got: function router(req, res, next){ self._dispatch(req, res, next); } – Nicolas S.Xu Nov 24 '13 at 08:03
  • Thanks for correcting me. It is not explained in express API. Do you know where I can get reference about this app.router middleware? – Nicolas S.Xu Nov 24 '13 at 08:05
  • 1
    @NicolasS.Xu that second `console.log` output looks okay. As for more information about it: [the source](https://github.com/visionmedia/express/blob/master/lib/router/index.js) might be a good place to start, and also [this posting](http://stackoverflow.com/questions/12695591/node-js-express-js-how-does-app-router-work) contains a bit more information. – robertklep Nov 24 '13 at 08:10