代码之家  ›  专栏  ›  技术社区  ›  Mikhail

在CORS请求后,AJAX无法在浏览器上设置Cookies。Set Cookie头只存在于FireFox中,不存在于Chrome中

  •  0
  • Mikhail  · 技术社区  · 6 年前

    Set-Cookie 响应中的标题,但略过 document.cookie

    请求代码:

    $.ajax({
       type: "POST",
       url: "https://my-site/mailcamp",
       contentType: "application/json",
       dataType: "json",
       processData:false,
       data: JSON.stringify(reqBody),
       success: function (data) {
          console.log(data);   
       },
       xhrFields: { withCredentials: true },
       crossDomain: true,
    })
    

    服务器响应:

    app.use('/*', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "https://www.texashunterproducts.com");
      res.header("Access-Control-Allow-Headers", "Origin, x-access-token, x-user-pathway, x-mongo-key, X-Requested-With, Content-Type, Accept");
      res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
      res.header("Access-Control-Allow-Credentials", true);
      next();
    });
    
    router.route('/mailcamp')
        .post(async (req, res, next) => {
            try { 
                res.setHeader('Set-Cookie', [`texaspopup=true`]);
                res.cookie("texcookienowpopupnow", "trueasheck")
                res.send("Send me dem cookiez");
            } catch(err) { next(err) }
        })
    

    我只是没有在document.cookie中看到这个。我有一些奇怪的矛盾:

    设置Cookie FireFox网络选项卡中的响应头:

    enter image description here enter image description here

    然而,它在Chrome中是完全缺失的!

    enter image description here

    文档.cookie 文档.cookie 无法使用找到我的密钥/值对 ctrl+f . 为什么?怎么回事?它不应该被隐藏,因为我没有添加 Httponly cookie上的标记,我直接将其发送到我正在查询的域。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Mikhail    6 年前

    这是个愚蠢的问题。是第三方饼干。虽然它是由外部域设置的,但只有浏览到发送cookie的域时,接收方才能通过doc.cookies读取它。最后,我使用此源代码在客户端本地设置cookie,并发送后续请求以完成服务器操作:

    https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework