简体   繁体   中英

AJAX fails to set Cookies on browser after CORS request. Set-Cookie header is present only in FireFox, not in Chrome

I am sending an AJAX request using JQuery to a NodeJS server, which SHOULD be setting cookies back to the client without a problem, but it's NOT. I can see the Set-Cookie headers in the response, yet skimming the document.cookie string does NOT contain my cookies,. If anyone could take a look over this code, I would much appreciate it.

Request Code:

$.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,
})

Server Response:

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) }
    })

I'm just NOT getting this in document.cookie. I have some strange inconsistencies:

I can clearly see the Set-Cookie response header in FireFox Network Tab:

在此处输入图像描述 在此处输入图像描述

However, it is completely missing in Chrome!

在此处输入图像描述

I'm not able to find the cookie when parsing document.cookie at all. I've copy+pasted the contents of document.cookie and can not find my key/value pair using ctrl+f . Why? What's going on here? It shouldn't be hidden because I'm not adding Httponly markers on the cookie, and I'm sending it directly to the domain that I am querying from.

This was a foolish problem. It's a third party cookie. While it is set by an external domain, it can't be read by the receiver via doc.cookies, only when browsing to the domain from which the cookie was sent. I ended up using code from this source to set a cookie locally within the client, as well as sending the subsequent request to accomplish the server action:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM