Setting Cookies with XMLHttpRequest

781 views
Skip to first unread message

Leila Hamon

unread,
Sep 11, 2015, 1:32:29 PM9/11/15
to Express
I'm trying to set a cookie using XMLHttpRequest. I'm seeing a "Set-Cookie" header in a response to an XHR post request, but I don't see the cookie in document.cookie. That's fine, though, I ultimately want cookies to not be exposed to the javascript environment, but I'm not seeing any cookies attached to any subsequent post requests from the script, and I thought that cookies were automatically attached to requests by the browser. Is this incorrect? I'm a little confused on whether the cookie is or isn't being set, and I could use some help in figuring this out.

Here is what the client side code looks like:

    (function() {
      var xhr = new XMLHttpRequest();
      var authUrl= "http://api.myserver.io/cookie"
      xhr.addEventListener("load", reqListener);
      xhr.open("POST", authUrl, true);
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.credentials = true;
      xhr.send();
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          debugger;
          // I'm not seeing anything in xhr.request
        }
      }
      var reqListener = function() {
        debugger;
      }
    })()


The server code is utilizing expreess and is handling the request to create a cookie with this function:

    var setCookie = function(req, res) {
      res.cookie('test-cookie', Date.now(), {
        maxAge: 3600000000,
        path:  '/' });
      res.status(200).end()
    }
Reply all
Reply to author
Forward
0 new messages