简体   繁体   中英

Set session value in callback (Node.js, express.js)

How to set session value in callback? Why it doesn't work?

app.get('/room/:id', function(req, res) {
    var room_id = req.param('id');
    room.getRoom(room_id, function(err, result) {
        if(result.length) {
            req.session.code_room = room_id;
        }
    }); 
    res.render('room.jade');
});

You probably should move res.render to the inside of callback function:

app.get('/room/:id', function(req, res) {
    var room_id = req.param('id');
    room.getRoom(room_id, function(err, result) {
        if(result.length && !err) {
            req.session.code_room = room_id;
        } else {
            //sorry...
            req.session.code_room = -1;
        }
        res.render('room.jade');
    }); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM