会话不存储在Express for Node.js中

时间:2012-06-05 10:54:45

标签: node.js express

我有以下路线基本上对登录表单中的帖子起作用。问题是当登录成功(找到成员并且密码匹配)时,member._id不会存储在会话中。

我的路线:

app.post('/signin', function(req, res) {
    Member.findOne({username: req.body.username}, function(error, member) {
        var matchPassword = crypto.createHmac('sha1', member.salt).update(req.body.password).digest('hex');
        if(member.password == matchPassword) {
            req.session.member_id = member._id;
            res.redirect('/' + member.username);
        }
    });
    res.redirect('/');
});

触发此路由时,我在控制台中收到以下错误:

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/Users/admin/Node Projects/sandboxProject/node_modules/express/node_modules/connect/lib/patch.js:62:20)
    at ServerResponse.header (/Users/admin/Node Projects/sandboxProject/node_modules/express/lib/response.js:280:8)
    at ServerResponse.redirect (/Users/admin/Node Projects/sandboxProject/node_modules/express/lib/response.js:413:10)
    at Promise.<anonymous> (/Users/admin/Node Projects/sandboxProject/app.js:109:8)
    at Promise.<anonymous> (/Users/admin/Node Projects/sandboxProject/node_modules/mongoose/lib/promise.js:120:8)
    at Promise.<anonymous> (events.js:64:17)
    at Promise.emit (/Users/admin/Node Projects/sandboxProject/node_modules/mongoose/lib/promise.js:59:38)
    at Promise.complete (/Users/admin/Node Projects/sandboxProject/node_modules/mongoose/lib/promise.js:70:20)
    at /Users/admin/Node Projects/sandboxProject/node_modules/mongoose/lib/query.js:1087:15

它似乎不喜欢“res.redirect('/'+ member.username);”在“req.session.member_id = member._id;”之后。这是因为它所在的Mongoose findOne回调的异步性质吗?我已经尝试从回调中删除res.redirect但会话数据没有存储,当我把它留在那里时,我收到“已发送的标题”错误。

我的配置:

app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.cookieParser());
    app.use(express.session({ secret: "blahblah" }));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

3 个答案:

答案 0 :(得分:8)

我有类似的问题。虽然我的问题是当我从会话中删除某些内容时,例如delete req.session.user,在重新加载和节点应用重启后它仍然存在。它只会在req.session.destroy()之后消失。

我查看了Node的会话middleware docs,发现他们有Session#save()方法。所以我在会话对象操作之后做了req.session.save()并确实解决了我的问题。试一试,看看它是否能解决你的问题。

答案 1 :(得分:4)

问题是Member.findOne是异步的。当它的回调执行时,res.redirect('/')已经执行,它设置了适当的HTTP响应头。您不能通过HTTP规则两次发送标头,因此错误Can't set headers after they are sent.

您可能希望将redirect('/')移动到密码匹配的else块中。

答案 2 :(得分:0)

我有类似的问题。 但我当时的问题是:

request.session.user = user;

我通过调试发现,当注释掉这一行时,不会发生此错误:

// request.session.user = user;

这是我的问题: express 4.x session-mongoose Can't set headers after they are sent(Been resolved)