• 25-Jan-2023
Lightrun Team
Author Lightrun Team
Share
This article is about fixing Sending cookie with fetch is working but not with axios in Axios Axios

Sending cookie with fetch is working but not with axios in Axios Axios

Lightrun Team
Lightrun Team
25-Jan-2023

Explanation of the problem

The developer is experiencing an issue with sending cookies using the Axios library while making a POST request to a server. The developer has verified that the cookie is present in their Chrome browser and has attempted to send the cookie in the request by setting the withCredentials property to true in the Axios configuration. However, the server logs do not show the cookie being received. The following code block shows the Axios configuration used for the request:

const request = axios.create({
  baseURL: 'https://x.sss.com',
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true,
  timeout: 300000,
  transformRequest: [function (data) {
    return JSON.stringify(data)
  }]
})

request({
  url: '/api/post',
  method: 'post',
  data: [1,2,3]
})

The developer has also attempted to send the cookie using the Fetch API and the server logs show that the cookie is being received in this case. The following code block shows the Fetch configuration used for the request:

fetch('https://x.sss.com/api/post', {
  'method': 'POST',
  'body': JSON.stringify([1,2,3]),
  'credentials': 'include',
  'mode': 'cors',
  'headers': {
    'accept': 'application/json, text/plain, */*', 'content-type': 'application/json'
  }
})

The developer also provides the HTTP response headers received from the server when making a request using the Fetch API, which includes the following headers related to CORS:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-requested-with,content-type
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin: http://127.0.0.1:1288
Access-Control-Max-Age: 3600

The developer is confused as to why the cookie is not being received in the request made using Axios but is being received in the request made using the Fetch API. It is likely that this issue may be related to CORS settings on the server, or some specific configuration in Axios library.

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for Sending cookie with fetch is working but not with axios in Axios Axios

The issue at hand is related to the handling of credentials when making cross-site requests using the axios library. By default, web browsers will not send cookies or HTTP auth headers when making a cross-origin request. This is a security measure to prevent malicious websites from stealing sensitive information stored in cookies or headers. However, in some cases, it is necessary to send these credentials across origins.

To solve this issue, axios has a feature called “withCredentials” that allows you to enable the sending of credentials (cookies or headers) with cross-site requests. This is done by setting the withCredentials property to true in the config object when creating an axios instance.

const axiosInstance = axios.create({
    withCredentials: true
});

However, when you use the transformRequest option, which allows you to modify the request data before it is sent to the server, it seems that the withCredentials option is not working as expected. The cookies or headers that were set to be sent with the request are not being sent.

const axiosInstance = axios.create({
    withCredentials: true,
    transformRequest: [(data, headers) => {
        headers['x-xsrf-token'] =  someCsrfToken
        return data;
    }]
});

To fix this issue, you can move the headers modification to the headers property of the config object instead of using the transformRequest option, as this way the withCredentials flag remains in effect.

const axiosInstance = axios.create({
    withCredentials: true,
    headers: {
      'x-xsrf-token':  someCsrfToken,
    }
  });

Or you can add withCredentials flag on the request object when creating a cookie on the server side, this will make sure that the cookie is created with the correct flag.

axios.post('https://yourserver.com/createCookie', {}, {withCredentials: true})

It is important to note that enabling the withCredentials option will only work if the server has explicitly set the Access-Control-Allow-Credentials header to true. This will allow the browser to include the credentials in the request and for the server to process them correctly.

Other popular problems with Axios

Problem: Handling CORS (Cross-Origin Resource Sharing) errors

When making cross-origin requests, the browser will automatically block the request if the server does not have the appropriate CORS headers set. This can lead to issues such as the following error message: “No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

Solution:

To solve this issue, you can use the “proxy” option in the Axios config to route the request through a server-side proxy. This proxy can add the necessary CORS headers to the request before it is sent to the server.

const axios = require('axios');

const instance = axios.create({
  baseURL: 'https://yourserver.com',
  proxy: {
    host: '127.0.0.1',
    port: 9000,
  },
});

Alternatively, you can set the headers directly on the server side.

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
});

Problem: Handling redirects

By default, Axios will automatically follow redirects, which can lead to issues such as infinite redirect loops.

Solution:

To solve this issue, you can set the “maxRedirects” option in the Axios config to limit the number of redirects that are followed.

const axios = require('axios');

const instance = axios.create({
  baseURL: 'https://yourserver.com',
  maxRedirects: 5,
});

Alternatively, you can set the “validateStatus” option in the Axios config to a function that will only allow certain status codes to be considered as successful. This can be used to prevent redirects that return a non-success status code from being followed.

const axios = require('axios');

const instance = axios.create({
  baseURL: 'https://yourserver.com',
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },
});

Problem: Handling timeouts

By default, Axios will wait indefinitely for a response from the server. This can lead to issues such as hanging requests and slow performance.

Solution:

To solve this issue, you can set the “timeout” option in the Axios config to a specific time in milliseconds.

const axios = require('axios');

const instance = axios.create({
  baseURL: 'https://yourserver.com',
  timeout: 5000,
});

Alternatively, you can set the “timeout” option in the config of a specific request.

axios.get('/longRequest', {
  timeout: 3000
});

It is important to note that setting a timeout value that is too short can lead to requests being cancelled before the server has had a chance to respond. Therefore, it is important to choose an appropriate timeout value based on the expected response time of the server.

A brief introduction to Axios

Axios is a popular JavaScript library for making HTTP requests. It is based on the promise API, which allows for a more elegant way of handling asynchronous requests. Axios can be used in both the browser and in Node.js environments and it supports all popular HTTP methods such as GET, POST, PUT, DELETE and PATCH.

Axios provides a simple and easy-to-use API for making requests. It allows you to set a wide range of options, such as headers, query parameters, and request data, in a single config object. Additionally, Axios allows you to intercept requests and responses, which can be useful for adding additional functionality such as logging, authentication, or error handling. Axios also supports features such as automatic retries, automatic JSON parsing and support for canceling requests. Axios also has a built-in feature that allows you to easily manage and maintain multiple instances of the library, each with its own set of configuration options, which is useful when working with different APIs or servers. Overall, Axios is a powerful and flexible library that can be used for a wide range of use cases, making it a popular choice among developers.

Most popular use cases for Axios

  1. Axios can be used for making HTTP requests to a server in a simple and consistent way. It is a popular JavaScript library that supports both Node.js and web browsers.
axios.get('https://api.example.com/users')
  .then(response => console.log(response.data))
  .catch(error => console.log(error));
  1. Axios can also be used to handle request and response interceptors, which allows for easy handling of global logic such as authentication and error handling.
axios.interceptors.request.use(config => {
  config.headers.Authorization = `Bearer ${token}`;
  return config;
});

axios.interceptors.response.use(response => {
  if (response.data.status === 'error') {
    throw new Error(response.data.message);
  }
  return response;
});
  1. Axios supports handling of multiple concurrent requests using the axios.all() method, which allows for easy handling of multiple responses in parallel.
axios.all([
  axios.get('https://api.example.com/users'),
  axios.get('https://api.example.com/posts')
])
.then(axios.spread((usersResponse, postsResponse) => {
  console.log(usersResponse.data);
  console.log(postsResponse.data);
}));
Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications. It’s a registration form away.

Get Lightrun

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.