I'm trying to authenticate express API back-end using Axios HTTP request call. I was able to see 'Set-Cookie' in the response header, but cookie was not set. Is it possible to set cookies through Axios HTTP calls?
Access-Control-Allow-Origin: * Connection: keep-alive Content-Length: 355 Content-Type: application/json; charset=utf-8 Date: Fri, 28 Sep 2018 05:59:01 GMT ETag: W/"163-PAMc87SVHWkdimTJca7oRw" Set-Cookie: token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; Max-Age=3.6; Path=/; Expires=Fri, 28 Sep 2018 05:59:04 GMT; HttpOnly X-Powered-By: Express
To make Axios send cookies in its requests automatically, we can set the withCredentials option to true . axios. get(BASE_URL + '/todos', { withCredentials: true });
Sending HTTP requests to your API with Axios is a fantastic tool. Axios is supported by all major browsers. The package can be used for your backend server, loaded via a CDN, or required in your frontend application.
The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.
Axios POST JSON request A POST request is created with post method. Axios automatically serializes JavaScript objects to JSON when passed to the post function as the second parameter; we do not need to serialize POST bodies to JSON.
Try this out!
axios.get('your_url', {withCredentials: true}); //for GET axios.post('your_url', data, {withCredentials: true}); //for POST axios.put('your_url', data, {withCredentials: true}); //for PUT axios.delete('your_url', data, {withCredentials: true}); //for DELETE
For more information on this from the axios docs:
"withCredentials indicates whether or not cross-site Access-Control requests should be made using credentials" - https://github.com/axios/axios
More detail on withCredentials:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With