Before I ask about app.router
I think I should explain at least what I think happens when working with middleware. To use middleware, the function to use is app.use()
. When the middleware is being executed, it will either call the next middleware by using next()
or make it so no more middleware get called. That means that the order in which I place my middleware calls is important, because some middleware depends on other middleware, and some middleware near the end might not even be called.
Today I was working on my application and had my server running in the background. I wanted to make some changes and refresh my page and see the changes immediately. Specifically, I was making changes to my layout. I couldn't get it to work so I searched Stack Overflow for the answer and found this question. It says to make sure that express.static()
is beneath require('stylus')
. But when I was looking at that OP's code, I saw that he had his app.router
call at the very end of his middleware calls, and I tried to figure out why that was.
When I made my Express.js application (version 3.0.0rc4), I used the command express app --sessions --css stylus
and in my app.js file the code came setup with my app.router
above both the express.static()
and require('stylus')
calls. So it seems like, if it comes already setup that way, then it should stay that way.
After re-arranging my code so I could see my Stylus changes, it looks like this:
app.configure(function(){
//app.set() calls
//app.use() calls
//...
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(__dirname + '/public', {maxAge: 31557600000}));
});
app.get('/', routes.index);
app.get('/test', function(req, res){
res.send('Test');
});
So I decided that the first step would be to find out why it is important to even have app.router
in my code. So I commented it out, started my app and navigated to /
. It displayed my index page just fine. Hmm, maybe it worked because I was exporting the routing from my routes file (routes.index). So next I navigated to /test
and it displayed Test on the screen. Haha, OK, I have no idea what app.router
does. Whether it is included in my code or not, my routing is fine. So I am definitely missing something.
So Here Is My Question:
Could somebody please explain what app.router
does, the importance of it, and where I should place it in my middleware calls? It would also be nice if I got a brief explanation about express.static()
. As far as I can tell, express.static()
is a cache of my information, and if the application can't find the requested page, it will check the cache to see if it exists.