在req.session.destroy()ExpressJS之前保存

时间:2014-02-11 15:23:26

标签: javascript node.js mongodb session express

我想在注销路径中销毁会话之前将会话值“图像位置”保存到数据库中

我采用的解决方案是:

app.get('/logout',function(req,res){

    Person.update({ username: req.session.user_name }, { $set: {lastimage: req.session.userimage[req.session.img_idx]}}, function(error,update)
            {
                if(update){ 
                req.session.destroy(function() {
                     res.end();
                });
                if(error){
                    console.log(error);
                    res.end();
                }

                }       

            });
});

但是当我使用这个获取位置路线时,任务就完成了,即人员db的值被更新,但作为回报,显示了一些奇怪的错误

TypeError: Cannot read property 'undefined' of undefined
    at options.key (/opt/expressjs/app.js:381:94)
    at callbacks (/opt/expressjs/node_modules/express/lib/router/index.js:164:37)
    at param (/opt/expressjs/node_modules/express/lib/router/index.js:138:11)
    at pass (/opt/expressjs/node_modules/express/lib/router/index.js:145:5)
    at Router._dispatch (/opt/expressjs/node_modules/express/lib/router/index.js:173:5)
    at Object.router (/opt/expressjs/node_modules/express/lib/router/index.js:33:10)
    at next (/opt/expressjs/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at resume (/opt/expressjs/node_modules/express/node_modules/connect/lib/middleware/static.js:65:7)
    at SendStream.error (/opt/expressjs/node_modules/express/node_modules/connect/lib/middleware/static.js:80:37)
    at SendStream.EventEmitter.emit (events.js:95:17)

为什么会如此。我正在使用ExpressJs会话和mongodb

P.S:行/opt/expressjs/app.js:381:94是

Person.update({ username: req.session.user_name }, { $set: {lastimage: req.session.userimage[req.session.img_idx]}}, function(error,update)

1 个答案:

答案 0 :(得分:1)

您是否尝试过保存

'req.session.userimage [req.session.img_idx]'在使用前的某些变量中?

例如:

var uName = req.session.user_name,
    uImage = req.session.userimage[req.session.img_idx];

Person.update({ username: uName }, { $set: {lastimage: uImage }}, function(error,update) { ...
顺便说一下,你可能会两次调用res.end(),这会让事情变得奇怪。

修改

app.get('/logout', function(req,res) {

    var uName  = req.session.user_name,
        uImage = req.session.userimage[req.session.img_idx];

    Person.update({ username: uName }, { $set: {lastimage: uImage }}, function(error,update) {

        if(error)
            console.log(error);

        // This actually destroys the session
        delete req.session;
        res.end();
    });
});