0

I am going crazy with cookies and ajax call.

My configuration is simple. I run a website on 8282 port, (localhost.com:8282). My website calls some webservices on 8080 port (localhost.com:8080). Of course I add a line in my hosts file to avoid localhost trouble :

127.0.0.1 localhost.com

I try to set a cookie when the webservice is called with ajax. Here is my response header that I can see with Chrome debugger :

Set-Cookie:token=Custom eyJ0aW1lc3RhbXAiOiIxNDI0NzE5Mzc5ODY3IiwgImlkIjoiNTRlNzZkZGU2ZDk3ZGM1MjYxZjQzMzFlIiwgInNpZ25hdHVyZSI6Im5tZnFGeEEvYlc0TFJGNFJNb3dBZXJZOUw0aWw0aEorcFh1YUt5b3VFK0k9In0=;domain=.localhost.com;path=/;

The cookie is never stored by Chrome. However, when I use Rest client extension and I call the same webservice, the cookie is stored by Chrome ! So my cookie is well formed but is not stored with ajax call.

ValentinV
  • 764
  • 1
  • 8
  • 17

2 Answers2

2

It's likely an issue with CORS (Cross Origin Resource Sharing, i.e the fact that the domain of the client and of the target of the AJAX call are not the same). For cookies to work well in a CORS configuration, you need to set the withCredentials flag to true. How to do so varies depending on you AJAX library (if you're using one).

See here: http://www.html5rocks.com/en/tutorials/cors/

Valentin Waeselynck
  • 5,950
  • 26
  • 43
  • Thank you for your help, is it considered as CORS issue even if the domain is the same and only the port change ? – ValentinV Feb 23 '15 at 20:38
0

In your close reponse of ajax you can set your cookie

document.cookie = "token=Custom eyJ0aW1lc3RhbXAiOiIxNDI0NzE5Mzc5ODY3IiwgImlkIjoiNTRlNzZkZGU2ZDk3ZGM1MjYxZjQzMzFlIiwgInNpZ25hdHVyZSI6Im5tZnFGeEEvYlc0TFJGNFJNb3dBZXJZOUw0aWw0aEorcFh1YUt5b3VFK0k9In0=;domain=.localhost.com;path=/";

Can an AJAX response set a cookie?

Community
  • 1
  • 1
head
  • 1
  • 2