In this article, we will see how to add headers to the Axios requests.

In some scenarios, while making requests with Axios, we may need to add custom headers to the request, such as authentication tokens, content types, or user agents. To do this, Axios provides a config object by which we can set the headers for the request.

Following is a an example of how we can add headers to Axios requests?

import axios from 'axios';

axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.put['Content-Type'] = 'application/json';

In the above example, we import Axios and set the Authorization header for all requests by modifying the headers.common object and also we set the Content-Type header for POST and PUT requests by modifying the headers.post and headers.put objects.

As an another way, we can also set the custom headers by passing the config object to the Axios.

Following is the example:

import axios from 'axios';

const config = {
  headers: { 'Authorization': 'Bearer ' + token }
};

axios.get('/api/data', config)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Explanation:

In the above example, we define a config object that contains the Authorization header with the authentication token and then pass theconfig object to the axios.get function along with the URL to make the GET request.

By modifying the config object, we can also set headers for other HTTP methods, such as POST, PUT, PATCH, and DELETE.

Following example show how to intercept the request and the modify the headers using the config object:

import axios from 'axios';

axios.interceptors.request.use(config => {
  config.headers['Authorization'] = 'Bearer ' + token;
  return config;
});

In the above example, we use the axios.interceptors.request.use function to intercept requests and modify the config object to add the Authorization header with the authentication token.

Categorized in:

Tagged in: