This is a TIP to help you past a common gotcha with Express 3 static files. This does not happen in Express 4
This is a quick tip for those of you experimenting with Node.js and the Express framework. Express allows us to create all of these wonderful rest based endpoints to give us all this great data, but sometimes you need to serve static files too. How else are you going to get you JS, CSS, etc files to the client?
Well many people do this setup or something similar:
app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(app.router); app.use(express.static(__dirname + '/public'));
Well it’s the last two lines
app.use(app.router); app.use(express.static(__dirname + '/public'));
You see, everyone tells you about serving static files up with this:
app.use(express.static(__dirname + '/public'));
So you put in at the end, right after:
And that’s the problem. You see app.use is called on app.router so now all requests will get caught by the app.router. Everything is called in order in the app.use chain.
To fix this simply make sure you call app.use(app.router) AFTER your other app.use expressions.
app.use(express.static(__dirname + '/public')); app.use(app.router);
Thanks so much for reading this, now upgrade to Express 4 and forget all of this, as router is not used in the middleware anymore.