当前位置 : 主页 > 网页制作 > Nodejs >

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

来源:互联网 收集:自由互联 发布时间:2021-06-16
我有以下路线,基本上从登录表单作用于帖子.问题是当登录成功(找到成员并且密码匹配)时,member._id不会存储在会话中. 我的路线: app.post('/signin', function(req, res) { Member.findOne({username: re
我有以下路线,基本上从登录表单作用于帖子.问题是当登录成功(找到成员并且密码匹配)时,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'));
});
我遇到了类似的问题.虽然我的问题是当我从会话中删除某些内容时,例如删除req.session.user,它会在重新加载和节点应用程序重新启动后仍然存在.它只会在req.session.destroy()之后消失.

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

网友评论