【问题标题】:Sending cookies to browser fails in Express在 Express 中向浏览器发送 cookie 失败
【发布时间】:2019-12-16 16:13:28
【问题描述】:

我能够成功创建我的 cookie,并且可以在控制台中清楚地看到它们。现在的问题是我想将这些 cookie 发送到浏览器,但我无法做到这一点。当我打开我的 Chrome 并转到 cookie 时,它​​们并不存在

我已将安全选项设置为 false 并将 httponly 设置为 false,但它似乎不起作用

    req.session.cart = cart;
    var cookieValue = JSON.stringify([req.session.cart],{secure:false, maxAge: 180 * 60 * 1000, httpOnly: false });       
    var cookie = req.cookies.cookieName;
        // no: set a new cookie
        res.cookie('cookieName',cookieValue);
        console.log('cookie created successfully');
        // yes, cookie was already present 
        console.log('cookie exists', cookieValue);
    res.redirect('/');

当我创建 cookie 时,它​​们必须出现在浏览器中

【问题讨论】:

  • 当您使用res.redirect 而不是res.send 时,cookie 会发生什么情况?因为我愿意打赌重定向也不会设置 cookie 数据。如果您要重定向,那么无论如何都没有理由设置任何 cookie。但是,如果您要提供真实页面,那么您通常希望将 cookie 管理作为中间件功能,例如它将以next() 结尾,而不是实际的响应操作(如sendrenderredirect);这将发生在链中的下一个函数中。

标签: node.js express session-cookies


【解决方案1】:

就像@Mike 'Pomax' Kamermans 提到的,我认为这可能与res.redirect 有关。尝试将它们添加到您的 / 路由中。像这样的:

// Requires cookie-parser
// https://expressjs.com/en/api.html#req.cookies
// https://github.com/expressjs/cookie-parser

app.post('/cart', function(req, res){
    req.session.cart = cart;
    var cookieValue = JSON.stringify([req.session.cart],{secure:false, maxAge: 180 * 60 * 1000, httpOnly: false });       
    var cookie = req.cookies.cookieName;
    if(!cookie) {
        res.cookie('cookieName',cookieValue);
        console.log('cookie created successfully');
    } else {
        console.log('cookie exists', cookieValue);
    }
    res.redirect('/');
});

app.get('/', function(req, res){
    if((typeof req.cookies == "object")&&(Object.keys(req.cookies).length>0)) {
        console.log("Cookies are present");
        // copy cookies from req to res
        for(var o=0; o<Object.keys(req.cookies).length; o++) {
            var key = Object.keys(req.cookies)[o];
            res.cookie(key,req.cookies[key]);
        }
    }
    res.status(200).send("OK");
});

【讨论】:

  • 谢谢大家的回复,我可以解决问题
猜你喜欢
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 2014-04-09
  • 2019-08-19
  • 1970-01-01
  • 2019-08-02
相关资源
最近更新 更多