Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty sending cookies with fetch requests in JavaScript

I have two separate services, a React single page application and an express API and I'm trying to communicate from the SPA to the API using the new fetch feature. Since the two services lie on different domains, I'm using a CORS middleware inside of the express application in order to make requests from the SPA to the API. I'm trying to make any fetch requests also include cookies so that way I can verify the cookies in my express application, for example

On 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 using document.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!

like image 651
Josh Black Avatar asked Apr 15 '15 22:04

Josh Black


People also ask

Are cookies sent on fetch requests?

Unless fetch() is called with the credentials option set to include , fetch() : won't send cookies in cross-origin requests. won't set any cookies sent back in cross-origin responses.

Is fetch better than XMLHttpRequest?

Fetch is a new native JavaScript API, supported by most browsers today. Fetch allows you to make network requests similar to XMLHttpRequest . According to Google Developers Documentation Fetch makes it easier to make asynchronous requests and handle responses better than with the older XMLHttpRequest .

Can we use fetch in JavaScript?

The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.


1 Answers

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

like image 171
Cordle Avatar answered Oct 04 '22 14:10

Cordle