Skip to content

Axios: Set Headers for GET/POST Requests

Last updated on July 7, 2023

To set headers for GET and POST requests in Axios, you can pass an object containing the headers as the third argument of the axios.get() or axios.post() method. Here’s an example:

import axios from 'axios';

// Set headers for GET request
axios.get('/api/data', {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-token'
  }
})
  .then(response => {
    // Process the response
    console.log(response.data);
  })
  .catch(error => {
    // Handle errors
    console.error('Error:', error.message);
  });

// Set headers for POST request
axios.post('/api/data', {
  data: 'some-data'
}, {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-token'
  }
})
  .then(response => {
    // Process the response
    console.log(response.data);
  })
  .catch(error => {
    // Handle errors
    console.error('Error:', error.message);
  });

In the examples above:

  • For the GET request, we pass an object as the second argument to axios.get(), and within that object, we define the headers property as another object containing the desired headers.
  • For the POST request, we pass an object as the third argument to axios.post(), and within that object, we define the headers property as another object containing the desired headers.

You can customize the headers according to your requirements. Replace 'Content-Type', 'Authorization', and 'your-token' with the actual header names and values you need.

By setting the headers, you can include additional information in the request, such as content type, authorization tokens, or any other headers specific to your API or server requirements.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments