Make Axios Send Cookies in Its Requests Automatically

Make Axios send cookies in its requests automatically

You can use withCredentials property.

XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.

axios.get(BASE_URL + '/todos', { withCredentials: true });

Also its possible to force credentials to every Axios requests

axios.defaults.withCredentials = true

Or using credentials for some of the Axios requests as the following code

const instance = axios.create({
withCredentials: true,
baseURL: BASE_URL
})
instance.get('/todos')

Pass cookie with axios request

There are two different HTTP clients involved here:

  • The http://localhost:3000/setcookie request is made by your browser and the browser stores the cookie.
  • The http://localhost:2999 request is made by your Node.js process, which knows nothing about the browser's cookies.

You would have to copy the cookies from the incoming request into the outgoing (axios) request, perhaps so:

axios.get(url, {
headers: {cookie: req.headers.cookie}
})

Neither withCredentials: true nor CORS settings are needed in this case, because both are relevant only if the HTTP client is a browser.

node.js axios request with cookies

Having the withCredentials key enabled (set to 'true') should solve your issue.

Please try this:

const
fs = require('fs'),
https = require('https'),
axios = require('axios');

function reqTest()
{

axios.default.request({
'url': 'google.com',
'method': 'post',
'headers':
{
'Cookie': 'cookie1=?; cookie2=?;'
},
'withCredentials': 'true' // ADD THIS LINE
}
).then(res => {
console.log(res);
})
}

You can also enable this property for all requests in this instance of axios, changing axios' defaults:

axios.defaults.withCredentials = true;

axios.post(url, body).then(...).catch(...); // withCredentials is automatically enabled

Please report results.

axios cannot send cookie with request even with withCredential: true

If you plan on using this mulitple times, then just create an axios config:

client/src/utils/axiosConfig.js

import axios from 'axios';

const baseURL = process.env.NODE_ENV === "development"
? "http://localhost:3001/"
: "http://example.com"

const app = axios.create({
baseURL,
withCredentials: true
})

/*
The below is required if you want your API to return
server message errors. Otherwise, you'll just get
generic status errors.

If you use the interceptor below, then make sure you
return an "err" (or whatever you decide to name it) message
from your express route:

res.status(404).json({ err: "You are not authorized to do that." })

*/
app.interceptors.response.use(
response => (response),
error => (Promise.reject(error.response.data.err))
)

export default app;

client/src/actions/exampleAction.js

import app from '../utils/axiosConfig';

export const exampleAction = () => (
app.get('orders') // this will be defined as baseURL + "orders" (http://localhost:3001/orders)
.then(res => console.log(res))
.catch(err => console.log(err))
)

Then for your API, instead of specifying CORS headers, you can simply use cors wherever you're defining your express middleware:

const cors = require('cors');
const origin = process.env.NODE_ENV === "development"
? "http://localhost:3000"
: "http://example.com"

app.use(
cors({
credentials: true,
origin
}),
);

Axios withCredentials customize which http cookie to send

That isn't how httpOnly cookies work. You don't get to access them or decide which gets sent from the browser.

It seems like your server-side code for the /RefreshToken route can easily just ignore the accessToken cookie and only pay attention to the refreshToken cookie. That's entirely up to your server code so you can just code it accordingly.

but is there a way to customize this to a specific cookie ?

No, not for httpOnly cookies. They are httpOnly for a reason - the client can't mess with them in any way.

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

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

Perserve cookies between requests using AXIOS (Node.js)

Well... I'm too lazy to do things the hard way, so I'd just do something like this, using axios-cookie-jar-support:

const axios = require('axios').default;
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
const tough = require('tough-cookie');

axiosCookieJarSupport(axios);

const cookieJar = new tough.CookieJar();

axios
.get('https://google.com', {
jar: cookieJar, // tough.CookieJar or boolean
withCredentials: true, // If true, send cookie stored in jar
})
.then(() => {
console.log(cookieJar);
});


Related Topics



Leave a reply



Submit