How to send authorization header with axios

Viewed 283748

How can I send an authentication header with a token via axios.js? I have tried a few things without success, for example:

const header = `Authorization: Bearer ${token}`;
return axios.get(URLConstants.USER_URL, { headers: { header } });

Gives me this error:

XMLHttpRequest cannot load http://localhost:8000/accounts/user/. Request header field header is not allowed by Access-Control-Allow-Headers in preflight response.

I have managed to get it work by setting global default, but I'm guessing this is not the best idea for a single request:

axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

Update :

Cole's answer helped me find the problem. I am using django-cors-headers middleware which already handles authorization header by default.

But I was able to understand the error message and fixed an error in my axios request code, which should look like this

return axios.get(URLConstants.USER_URL, { headers: { Authorization: `Bearer ${data.token}` } });
12 Answers

Rather than adding it to every request, you can just add it as a default config like so.

axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}` 

You are nearly correct, just adjust your code this way

const headers = { Authorization: `Bearer ${token}` };
return axios.get(URLConstants.USER_URL, { headers });

notice where I place the backticks, I added ' ' after Bearer, you can omit if you'll be sure to handle at the server-side

Instead of calling axios.get function Use:

axios({ method: 'get', url: 'your URL', headers: { Authorization: `Bearer ${token}` } })

You can try this.

axios.get(
    url,
    {headers: {
            "Access-Control-Allow-Origin" : "*",
            "Content-type": "Application/json",
            "Authorization": `Bearer ${your-token}`
            }   
        }
  )
  .then((response) => {
      var response = response.data;
    },
    (error) => {
      var status = error.response.status
    }
  );
const response=await axios(url,
    method:"GET"
    {
     headers: {
        "Authorization" : `Bearer ${token}`
      }
    })

create a new axios instace for your request

  const instance=axios.create({
    baseURL:'www.google.com/'
    headers:{
        'Content-Type':'application/json',
                    'Acess-Control-Allow-Origin':'*',
                    'Authorization':`Bearer ${token}`,
                    'Accept': "application/json"
        }
    })

await instance.get(url,data)

Install the cors middleware. We were trying to solve it with our own code, but all attempts failed miserably.

This made it work:

cors = require('cors')
app.use(cors());

Original link

This is the Postman way of doing it:

headers: {
    'Authorization': `Basic ${Buffer.from('username:password').toString('base64')}`
}
res.setHeader('Access-Control-Allow-Headers',
            'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');

Blockquote : you have to add OPTIONS & Authorization to the setHeader()

this change has fixed my problem, just give a try!

Related