Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Axios support Set-Cookie? Is it possible to authenticate through Axios HTTP request?

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 
like image 658
Mandakh Avatar asked Sep 28 '18 05:09

Mandakh


People also ask

How do I send a cookie with Axios request?

To make Axios send cookies in its requests automatically, we can set the withCredentials option to true . axios. get(BASE_URL + '/todos', { withCredentials: true });

Does Axios work with HTTP?

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.

What does set-cookie do?

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.

How does Axios request work?

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.


1 Answers

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

like image 53
Aaron Avatar answered Oct 05 '22 18:10

Aaron