Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express serves index.html even when my routing is to a different file

I have a public directory with the files index.html and index-08.html in it.

With the code below, I expect index-08.html to be served. But instead, index.html gets served with a browser request of localhost:3000

app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
    res.sendFile('public/index-08.html');
});

But if I change the file name of index.html to something else, say not-index.html, then the correct file index-08.html gets served.

Can you please help me understand why this happens ?

like image 763
Kaya Toast Avatar asked Aug 06 '14 17:08

Kaya Toast


1 Answers

This is because you declared app.use(express.static) before app.get('/'). Express checks routes in the order they are declared, and since index.html is a default filename which is used by static middleware, it shows index.html content.

To fix this you may either put app.use(express.static) after app.get('/'), or set index property of static second argument to non-existing file (false doesn't seem to work):

app.use(express.static(path.join(__dirname, 'public'), {index: '_'}));
like image 103
Oleg Avatar answered Oct 23 '22 18:10

Oleg