How to send the authorization header using Axios
By Flavio Copes
Learn how to send the Authorization header with Axios by adding a headers object to the config argument of axios.post() and axios.get() requests.
To send the Authorization header with Axios, add a headers object to the request config. For axios.get() the config is the second argument. For axios.post() it’s the third, because the second is the request body.
Most APIs today use a bearer token, so the header looks like this:
const token = '..your token..'
axios.get('https://api.stripe.com/v1/charges', {
headers: {
'Authorization': `Bearer ${token}`
}
})
(the authorization scheme might differ, check the docs of the API you’re using)
Setting headers in a GET request
Pass a second object to the axios.get() call. For example this is a GitHub GET request to /user:
axios.get('https://api.github.com/user', {
headers: {
'Authorization': `token ${access_token}`
}
})
.then((res) => {
console.log(res.data)
})
.catch((error) => {
console.error(error)
})
Setting headers in a POST request
With POST, the arguments shift by one. You might already be using the second parameter to send data, so the config object moves to third position:
axios.post(url, {
title: 'Hello World'
}, {
headers: {
'Authorization': `Bearer ${token}`
}
})
The first object after the URL is the body. The second is the configuration, where you add the headers property.
A common mistake
Watch out for this one. If you forget the data argument and pass the config as the second parameter:
axios.post(url, {
headers: {
'Authorization': `Bearer ${token}`
}
})
Axios won’t complain. It sends your headers object as the request body, and no Authorization header is set. The server answers with a 401, and the code looks correct at first glance.
If your POST has no body to send, pass null or an empty object as the second argument, then the config as the third.
Basic authentication
I was doing some work with the WordPress API, and I had to authenticate to perform a POST request to a website.
The easiest way for me was to use basic authentication, where the token is the username and password joined by a colon, encoded in base64.
I was using Axios, so I set the Authorization header to the POST request in this way:
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}`
},
})Related posts about js: