javascript - 使用express更新cookie在nodejs中不起作用

标签 javascript node.js express cookies

我在登录后创建了一个登录 cookie,但是当我尝试更新其中的数据时,它给了我一个错误

Can't set headers after they are sent.

我的代码如下。

/* Logout to main user. */ /* Not Working  */
router.get('/logoutToMain', mustBe.authorized('supportuser'), function (req, res) {
    var loginSealed = req.cookies[req.ApplicationCookies.LoginCookie];
    if (loginSealed != undefined) {
        iron.unseal(loginSealed, req.Security.CookiePassword, iron.defaults, function (err, unsealed) {
            if (!err) {
                unsealed.SupportUser = null;
                iron.seal(unsealed, req.Security.CookiePassword, iron.defaults, function (err, sealed) {
                    if (!err) {
                        res.cookie(req.ApplicationCookies.LoginCookie, sealed, { expires: new Date(Date.now() + 432000), httpOnly: true, ephemeral: true });
                    }
                });
                //res.cookie(req.ApplicationCookies.LoginCookie, unsealed, { expires: new Date(Date.now() - 1000), httpOnly: true });
            }
        });
    }
    res.redirect('/');
});

虽然当我删除这个 cookie 时,它​​仍然有效。 (以下代码)

/* Logout action. */ /*  Working  */
router.get('/logout', mustBe.authenticated(), function (req, res) {
    var LoginCookie = req.cookies[req.ApplicationCookies.LoginCookie];
    if (LoginCookie != undefined) {
        res.cookie(req.ApplicationCookies.LoginCookie, null, { expires: new Date(Date.now() - 1000), httpOnly: true });
    }
    res.redirect('/');
});

下面的代码为登录用户创建 cookie

var LoggedinEmployee = {
    EmployeeID : recordset[0][0].EmployeeId,
    EmployerID : recordset[0][0].EmployerId,
    EmployerName : recordset[0][0].EmployerName,
    AccountName : Employer.AccountName,
    EmpLevel : recordset[0][0].EmpLevel,
    EmployeeName : recordset[0][0].EmployeeName,
    CorpId: recordset[0][0].CorpID,
    Login: user.Login,
    Password: user.Password,
    SupportUser: null
};
iron.seal(LoggedinEmployee, req.Security.CookiePassword, iron.defaults, function (err, sealed) {
    if (!err) {
        res.cookie(req.ApplicationCookies.LoginCookie, sealed, { expires: new Date(Date.now() + 432000), httpOnly: true, ephemeral: true });
        req.ActionOutput.Status = req.ActionStatus.Success;
        req.ActionOutput.Message = 'Logged In. Redirecting to dashboard...';
        res.send(JSON.stringify(req.ActionOutput));
    } else {
        req.ActionOutput.Status = req.ActionStatus.Error;
        req.ActionOutput.Message = 'System Error';
        res.send(JSON.stringify(req.ActionOutput));
    }
});

最佳答案

了解 Node.js 异步行为。在此代码中:

setTimeout(function(){
  console.log(1);
},0);
console.log(2);

output:
2
1

将是输出。为什么? 因为 Node.js 在一系列“滴答”中运行,这些“滴答”是队列中一个接一个运行的执行实例。在其他实例完成之前,下一个实例无法运行。每当 JavaScript 遇到“回调”时,它就会将其插入队列并执行下一条语句。它是非阻塞的。 setTimeout 将“注册”回调并立即返回,将控制流移动到下一行。当该实例完成时,将调用下一个回调。

在您的代码中 res.redirect('/');不会等待iron.unseal完成并立即执行,发送响应。之后,回调将被调用,res.cookie 将执行,发现响应已发送,导致抛出异常。移动 res.redirect('/');在 res.cookie 之后。

router.get('/logoutToMain', mustBe.authorized('supportuser'), function (req, res) {
    var loginSealed = req.cookies[req.ApplicationCookies.LoginCookie];
    if (loginSealed != undefined) {
        iron.unseal(loginSealed, req.Security.CookiePassword, iron.defaults, function (err, unsealed) {
            if (!err) {
                unsealed.SupportUser = null;
                iron.seal(unsealed, req.Security.CookiePassword, iron.defaults, function (err, sealed) {
                    if (!err) {
                        res.cookie(req.ApplicationCookies.LoginCookie, sealed, { expires: new Date(Date.now() + 432000), httpOnly: true, ephemeral: true });
                    }
                    res.redirect('/');
                });
                //res.cookie(req.ApplicationCookies.LoginCookie, unsealed, { expires: new Date(Date.now() - 1000), httpOnly: true });
            } else {
              res.redirect('/');
            }
        });
    } else {
      res.redirect('/');
    }
});

使用 Promise 或 wait 来改进你的代码并度过回调 hell 。

关于javascript - 使用express更新cookie在nodejs中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36541612/

相关文章:

javascript - 如何检查 javascript 函数是否准备就绪/完成 (jQuery)

javascript - Multer 看不到上传的图片

javascript - Express.js 或 React.js 中的通用用户名/密码身份验证

node.js - 如何使用 baucis 在 POST 请求后获取插入的 mongo id

javascript - Express - 如何从 POST 表单获取数据

node.js - 如何在 krakenjs 中使用中间件来实现特定路由?

javascript - 如何在 Android 上以编程方式退出全屏视频?

javascript - javascript onkeydown 问题 - event.which 只给出大写字符

javascript - VueJS 方法返回 "Native Code"消息

javascript - Mongodb 位置运算符不起作用