Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
494 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...