Kinda Code
Home/React/Axios: Set Headers in GET/POST Requests

Axios: Set Headers in GET/POST Requests

Last updated: February 10, 2023

This quick and straight-to-the-point article shows you how to set headers when sending GET and POST requests with Axios. Without any further ado (like talking about what Axios is or rambling about its history), let’s get started.

Set headers in a GET request

When calling the axios.get() method to perform a GET request, we pass our custom headers object in the second argument (the first argument is the URL), like this:

const res = await axios.get(
    'https://non-existing-api.kindacode.com/products',
    {
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        Authorization: 'Bearer YOUR_AUTH_TOKEN',
      },
    }
);

console.log(res.data);

Alternative:

const res = await axios('http://localhost:3000/api/v1/users', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
});

console.log(res.data);

Set headers in a POST request

To send a POST request with custom headers, you can call the axios.post() method as follows:

const res = await axios.post(
    'https://www.kindacode.com/fake-api/endpoint',
    {
      // request body data
      message: 'Hello KindaCode.com',
    },
    {
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer 123456',
      },
    }
);

The first argument is your API URL, the second argument is the data your want to post, and the third argument is the options object. Set your headers in the third argument.

Alternative:

const res = axios('https://www.kindacode.com/fake-api/endpoint', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer 1234567890',
    }, 
    // request body
    data: {
      message: 'Hello World',
    },
});

That’s it. Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Related Articles