express 中设置 cookie 的小坑
错误代码
res.cookie 在异步函数外时,可以正常设置,当res.cookie 在异步函数内时不能正常设置。将最后一句res.redirect('/')也放进异步函数中时,可以正常运行。
router.post('/doLogin', (req, res, next) => { var md5 = crypto.createHash('md5'); (async () => { var Users = await myModel.Users.findOne({ where: { userId: req.body.userId, } }); if (Users !== null && Users.psw === md5.update(req.body.psw).digest('base64')) { console.log("OK!"); res.cookie('remember', req.body.userId, { maxAge: 900000, domain: 'localhost' }); } else { console.log("NO!"); res.clearCookie('remember'); } })();
res.redirect('/');
});
改正
router.post('/doLogin', (req, res, next) => { var md5 = crypto.createHash('md5'); (async () => { var Users = await myModel.Users.findOne({ where: { userId: req.body.userId, } }); if (Users !== null && Users.psw === md5.update(req.body.psw).digest('base64')) { console.log("OK!"); res.cookie('remember', req.body.userId, { maxAge: 900000, domain: 'localhost' }); res.redirect('/'); } else { console.log("NO!"); res.clearCookie('remember'); res.redirect('/'); } })(); });