Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve static files and app.get conflict using Express.js

I have this piece of code here:

var express = require('express')
  , http = require('http')

var app = express();
var server = app.listen(1344);
var io = require('socket.io').listen(server);


app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'secret'}));


app.get('/', function(req, res){
    if(req.session){
        console.log(req.session);
    }
    console.log('ok');

});

The code inside the app.get() callback is not being called. If I comment out the app.use(express.static(__dirname + '/public')) line, then the callaback works. I've tried changing the order, but its like a lottery! I would prefer to know whats going wrong here.

I'm sure this have to do with lack of knowledge from my part on how the middleware is called. Can someone help me understand this problem?

Basically I just want to perform some logic before the files are served and the index.html is load on the browser. By the way placing the app.get() before the app.use(express.static()) line, does not did the trick!

like image 1000
limoragni Avatar asked Apr 18 '13 16:04

limoragni


1 Answers

Your static file middleware should go first.

app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'secret'}));

And you should be adding a use for app.router as well.

app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'secret'}));
app.use(app.router);

Middleware is processed in order for each request. So if you have an index.html in your static files then requests for yourdomain.com/ will never make it to the app.router because they will get served by the static file handler. Delete index.html and then that request will flow through to your app.router.

like image 138
Daniel Avatar answered Oct 21 '22 12:10

Daniel