简体   繁体   中英

How to let ajax request set a cookie coming from response header in JavaScript?

I'm not really sure how to phrase the question properly but here's my scenario. We have a pixel library (service A) which calls our own separate service (service B) to get a piece of information which works perfectly. We fixed CORS issue by nginx with this header.

access-control-allow-credentials:true
access-control-allow-headers:Authorization, Content-Type, If-None-Match
access-control-allow-methods:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin:*

If I call service B directly from browser by going to http://service-b I get these response headers.

access-control-allow-credentials:true
access-control-allow-headers:Authorization, Content-Type, If-None-Match
access-control-allow-methods:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin:*
access-control-expose-headers:WWW-Authenticate, Server-Authorization
access-control-max-age:86400
cache-control:max-age=600
Connection:keep-alive
content-encoding:gzip
Content-Length:56
Content-Type:text/plain; charset=utf-8
Date:Mon, 27 Jun 2016 17:36:22 GMT
Expires:Mon, 27 Jun 2016 17:46:22 GMT
set-cookie:name=value; Max-Age=14515200; Expires=Mon, 12 Dec 2016 17:36:22 GMT; Path=/

And I can see from Chrome developer tool that the cookie is set properly.

However, if I call service B from jQuery from a different domain like this.

 $.ajax({
   url: 'http://service-b/',
   type: 'GET',
   dataType: 'json',
   xhrFields: {
     withCredentials: true
   }
 }); 

Here's the response I get.

access-control-allow-credentials:true
access-control-allow-headers:Authorization, Content-Type, If-None-Match
access-control-allow-methods:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin:http://web.local
access-control-expose-headers:WWW-Authenticate, Server-Authorization
access-control-max-age:86400
cache-control:max-age=600
Connection:keep-alive
content-encoding:gzip
Content-Length:56
Content-Type:text/plain; charset=utf-8
Date:Mon, 27 Jun 2016 17:29:02 GMT
Expires:Mon, 27 Jun 2016 17:39:02 GMT

I don't see the set-cookie header and no cookie is set. I realized that this might be CORS issue but we wide open CORS already since we control both services internally. Am I missing anything? And how do I solve this issue?

Even if you opened CORS, the cookies from different domain won't be available directly across the domains. Cookies are always domain specific and as you said, you are calling the service from different domain, the cookies won't be available like this. You can set response headers instead of a cookie value.

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