Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expressjs order of app.router and express.static

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?

like image 773
tommyd456 Avatar asked Jan 11 '23 14:01

tommyd456


1 Answers

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

like image 58
Oleg Avatar answered Jan 16 '23 22:01

Oleg