我有以下路线,基本上从登录表单对帖子起作用。问题是当登录成功时(找到成员并且密码匹配),成员._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'));
});