Difficulty sending cookies with fetch requests in JavaScript
The fetch polyfill library you are using is not as of this writing up-to-spec. For credentials, it expects 'cors' to be the value as opposed to 'include'. I would edit my local copy of fetch.js on line 264 to accommodate the standard, submit a pull request, and be on the lookout for a better supported polyfill library.
See open issue: https://github.com/github/fetch/issues/109
https://github.com/github/fetch
https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch
Related videos on Youtube
Josh Black
Updated on September 14, 2022Comments
-
Josh Black over 1 year
I have two separate services, a
React
single page application and anexpress
API and I'm trying to communicate from the SPA to the API using the newfetch
feature. Since the two services lie on different domains, I'm using a CORS middleware inside of theexpress
application in order to make requests from the SPA to the API. I'm trying to make anyfetch
requests also include cookies so that way I can verify the cookies in myexpress
application, for exampleOn the client side:
fetch('http://localhost:8000/hello', { credentials: 'include', mode: 'cors' }).then(/* ... */)
On the server side:
var app = express(); app.use(cors({ credentials: true }); app.use(cookieParser()); app.get('/hello', function (req, res) { // Try and find the cookies sent with the request console.log(req.cookies); res.status(200).json({ message: 'cookies received!' }); });
However, no matter what I try I still cannot access any cookies on the
request
object even though I can access them through usingdocument.cookies
.An example cookie:
name: token value: TOKEN_VALUE domain: localhost path: / http: false secure: false
Does anyone have suggestions on how to approach this? Any help would be greatly appreciated!
-
Cordle almost 9 yearsThere are already pull requests on the repo to fix the issue: github.com/github/fetch/pull/113/files
-
shangsunset about 8 yearsHi, i had the same issue. changing to 'cors' instead of 'include' didnt solve the problem for me :(
-
shangsunset about 8 yearsthis is my question: stackoverflow.com/questions/35612226/…
-
svp about 6 yearsI still face the same issue even after using credential as include or same-orgin after using whatg-fetch 2.0.3.
-
atom88 over 4 yearsI must be on the latest version, because 'cors' wasn't valid and fetch threw and error. This is the spec and I don't see 'cors' as an option? developer.mozilla.org/en-US/docs/Web/API/Request/credentials