Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser cannot read and send cookies with fetch api even set credentials to include on cross origin request

Fetching cross origin request, Chrome cannot read set-cookie even if I set the credentials: 'include' and the server gives:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://127.0.0.1:3000

chrome

safari

It's a react(^16.6.3) project with fetch api

I tried Chrome, Safari, Firefox and mobile browsers, but all these browsers can not read and save cookies. In chrome there's no Set-Cookie field, but exist in Safari and Firefox.

empty cookies

And when I use postman to test it, it will be ok, the next request will send the cookies.

fetch('http://API_ROOT/api', {
  credentials: 'include',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=utf-8',
  },
  method: 'POST',
  body: JSON.stringify({})
});

Expect the browser to save and send cookie.

like image 311
TaoPaipai Avatar asked Oct 28 '25 13:10

TaoPaipai


1 Answers

Many other advices always say: set credentials: 'includes' and server side Access-Control-Allow-Credentials value to true. But I checked your code and response are both ok.

So maybe the cookie are expired?

Or maybe your browser disabled third party cookies?

withCredentials MDN

Third-party cookies

Note that cookies set in CORS responses are subject to normal third-party cookie policies. In the example above, the page is loaded from foo.example, but the cookie on line 22 is sent by bar.other, and would thus not be saved if the user has configured their browser to reject all third-party cookies.

like image 76
FaiChou Avatar answered Oct 30 '25 05:10

FaiChou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!