4

To configure my Expressjs app I have these two lines (amongst others):

...
app.use(express.static(__dirname + '/public'));
app.use(app.router);
...

I've read that the recommendation is to put the router before static but when I do my Angularjs app renders a blank page. When they are in the order shown the views render normally.

Why is this?

tommyd456
  • 10,443
  • 26
  • 89
  • 163
  • Where did you read that router should come before static? That does not sound right. You want static before router (as you have it) Do you have a link to the reference where you read otherwise? – Hector Correa May 12 '14 at 18:50
  • here's an example - I was looking at the last answer and while it's not the official correct one it seems to have a lot of support. http://stackoverflow.com/questions/13254549/in-express-what-does-app-router-do-exactly – tommyd456 May 12 '14 at 18:56
  • but I'm sure I've seen other examples too of having the router first – tommyd456 May 12 '14 at 18:57
  • and while not explicitly referencing the point, I noticed whilst looking at the sample docs for Passportjs the router appears first - on the ones I've seen anyway. – tommyd456 May 12 '14 at 19:05
  • This seems to be so confusing that Express 4.x got rid of it: https://github.com/visionmedia/express/wiki/New-features-in-4.x – Hector Correa May 12 '14 at 19:09
  • Yeah thinking of upgrading to 4 at some point! – tommyd456 May 12 '14 at 19:20

1 Answers1

9

It is the best to explain with an example. Let's say, you have an en.json file and you also have a route:

app.get('/en.json', function(req, res) {
    res.send('some json');
});

If you put

app.use(app.router);

before

app.use(express.static(__dirname + '/public'));

router will have a priority over static file, and user will see some json, otherwise en.json file will be served.

So if you don't have such collisions it doesn't matter which order you choose.

P.S. Note that if you're using Express 4 you may see this error:

Error: 'app.router' is deprecated!
Please see the 3.x to 4.x migration guide for details on how to update your app.

On the wiki page @HectorCorrea has shared in comments there is an explanation of this error:

no more app.use(app.router)

All routing methods will be added in the order in which they appear

Hope this helps

Oleg
  • 22,300
  • 9
  • 68
  • 84
  • 3
    This gives info on resolving the 'app.router is deprecated' err in Express 4 - https://github.com/strongloop/express/wiki/New-features-in-4.x – Carol Skelly Sep 23 '14 at 12:57