Doug
Doug

Reputation: 7057

Web Browser Does Not Set cookie on an Ajax Call

I'm very confused. I've got an AJAX call which causes a login form to be processed, and creates a cookie on a successful login. The web browser is not registering the cookie.

In troubleshooting, I isolated it down to something to do with the AJAX calling the site, rather than navigating directly.

e.g. I created a simple page "test" which returns the following output:

HTTP/1.1 200 OK
X-Powered-By: Express
Set-Cookie: token=ABCDEFG; Domain=localhost; Path=/
Content-Type: application/json; charset=utf-8
Content-Length: 19
ETag: W/"13-S4werj8PuppRlonJZs+jKA"
Date: Wed, 23 Sep 2015 22:09:03 GMT
Connection: keep-alive

{"message":"value"}

If I navigate directly to the page, the cookie is created in the browser.

If I make an AJAX call to the page, the cookie is not created in the browser. e.g:

$.get('http://localhost:8081/test');

I've found similar posts which state that this happens with AJAX if the domain or the path are not defined, but as you can see, I defined these and still no dice.

If it matters, the majority of my testing has been on Firefox, but I did do at least a couple of tests on Chrome.

Any help you have would greatly be appreciated. I'm confused by this, as everything I read suggests this should be possible.

To clarify further: 1) I'm not seeing the cookie created when reviewing CookieManager+ addon for Firefox. 2) I'm also not seeing the cookie added to subsequent requests to the same host (even the same port). 3) What I read seems to suggest that cookies are tied to a host, not a port (But that doesn't seem to be the issue based on #1 and #2): Are HTTP cookies port specific?

Upvotes: 0

Views: 247

Answers (2)

Doug
Doug

Reputation: 7057

If you're trying to do this in Angular, as I was, this is how you do it there:

$http doesn't send cookie in Requests

config(function ($httpProvider) {
    $httpProvider.defaults.withCredentials = true;

Upvotes: 0

duncanhall
duncanhall

Reputation: 11431

Try setting withCredentials in your request:

$.get('http://localhost:8081/test', {xhrFields: {withCredentials: true}});

Alternatively try setting the crossDomain value:

$.ajax({type:"GET", url:"localhost:8081/test", crossDomain:true});

Upvotes: 1

Related Questions