/

How to Send the Authorization Header Using Axios

How to Send the Authorization Header Using Axios

In this tutorial, we will learn how to send the authorization header using Axios, a popular JavaScript library for making HTTP requests.

To set headers in an Axios POST request, you need to pass a third object to the axios.post() call. Typically, the second parameter is used to send data, so if you pass two objects after the URL string, the first one should be the data and the second one should be the configuration object. In the configuration object, you can add a headers property containing another object.

Here’s an example of setting headers in a POST request using Axios:

1
2
3
4
5
6
7
8
9
axios.post(url, {
data: {
...
}
}, {
headers: {
...
}
})

If you want to set the authorization header, you can do it like this:

1
2
3
4
5
6
7
8
9
10
11
const token = '..your token..'

axios.post(url, {
data: {
...
}
}, {
headers: {
'Authorization': `Basic ${token}`
}
})

Please note that the authorization token might differ depending on the application you’re using.

For setting headers in an Axios GET request, you need to pass a second object to the axios.get() call. Here’s an example of a GitHub GET request to /user:

1
2
3
4
5
6
7
8
9
10
11
axios.get('https://api.github.com/user', {
headers: {
'Authorization': `token ${access_token}`
}
})
.then((res) => {
console.log(res.data);
})
.catch((error) => {
console.error(error);
})

I recently had to authenticate with the WordPress API to perform a POST request on a website. The easiest way for me was to use basic authentication. Since I was using Axios, I set the Authorization header of the POST request like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const username = ''
const password = ''

const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')

const url = 'https://...'
const data = {
...
}

axios.post(url, data, {
headers: {
'Authorization': `Basic ${token}`
},
})

That’s it! Now you know how to send the authorization header using Axios in various types of requests. Happy coding!

tags: [“Axios”, “authorization header”, “HTTP requests”, “POST request”, “GET request”, “basic authentication”]