149

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}` } });
Nagama Inamdar
  • 2,851
  • 22
  • 39
  • 48
foobar
  • 3,849
  • 8
  • 22
  • 32

12 Answers12

105

On non-simple http requests your browser will send a "preflight" request (an OPTIONS method request) first in order to determine what the site in question considers safe information to send (see here for the cross-origin policy spec about this). One of the relevant headers that the host can set in a preflight response is Access-Control-Allow-Headers. If any of the headers you want to send were not listed in either the spec's list of whitelisted headers or the server's preflight response, then the browser will refuse to send your request.

In your case, you're trying to send an Authorization header, which is not considered one of the universally safe to send headers. The browser then sends a preflight request to ask the server whether it should send that header. The server is either sending an empty Access-Control-Allow-Headers header (which is considered to mean "don't allow any extra headers") or it's sending a header which doesn't include Authorization in its list of allowed headers. Because of this, the browser is not going to send your request and instead chooses to notify you by throwing an error.

Any Javascript workaround you find that lets you send this request anyways should be considered a bug as it is against the cross origin request policy your browser is trying to enforce for your own safety.

tl;dr - If you'd like to send Authorization headers, your server had better be configured to allow it. Set your server up so it responds to an OPTIONS request at that url with an Access-Control-Allow-Headers: Authorization header.

Ashelyn Dawn
  • 1,521
  • 1
  • 14
  • 17
  • 14
    Thank you, Cole! Your 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}\` } });` – foobar Jun 27 '17 at 08:25
  • 2
    You're welcome! I run into this sort of issue with my APIs all the time. Just glad I could help you understand the process it has to go through. – Ashelyn Dawn Jun 27 '17 at 19:09
  • Well fu¢k this i spent the whole night fighting with this axios cors origin issue. If i just found this answer 10 hours ago – anouar es-sayid Oct 10 '22 at 08:27
93

This has worked for me:

let webApiUrl = 'example.com/getStuff';
let tokenStr = 'xxyyzz';
axios.get(webApiUrl, { headers: {"Authorization" : `Bearer ${tokenStr}`} });
Tony
  • 16,527
  • 15
  • 80
  • 134
sean717
  • 11,759
  • 20
  • 66
  • 90
  • 15
    There's less details in the answer compared to the above but this is the answer what everyone is looking for when they search google. – Black Mamba May 11 '20 at 11:54
80

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}` 
Canaan Etai
  • 3,455
  • 2
  • 21
  • 17
50

Try this :

axios.get(
    url,
    {headers: {
        "name" : "value"
      }
    }
  )
  .then((response) => {
      var response = response.data;
    },
    (error) => {
      var status = error.response.status
    }
  );
David Schumann
  • 13,380
  • 9
  • 75
  • 96
Matija Župančić
  • 1,080
  • 2
  • 11
  • 21
  • 1
    So header name will be 'Access-Control-Allow-Headers' and value is what you want. – Matija Župančić May 31 '17 at 11:06
  • So, you mean I'd have something like: axios.get( url, { headers: { 'Access-Control-Allow-Headers': 'Bearer ' } } ) ? That doesn't work. – foobar May 31 '17 at 13:20
  • 12
    I believe it should be { 'Authorization': 'Bearer ' } – John Harding Jun 23 '17 at 15:15
  • 1
    The first comment is incorrect; `Access-Control-Allow-Headers` is a *response* header and must be sent from the server to the browser. @JohnHarding has it correct; the appropriate header to set *in a request* is an Authorization header. Also, headers which do not have spaces or other special characters do not need to be quoted. Since the question pertains specifically to the Authorization header, and this provides only general advice with only "Try this" by way of explanation, I cannot in good faith upvote it. – Heretic Monkey Aug 28 '21 at 17:24
9

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

Gianfranco P.
  • 10,049
  • 6
  • 51
  • 68
Jalasem
  • 27,261
  • 3
  • 21
  • 29
  • 6
    Normally (by spec) there is a space, not dash (`-`), between the auth scheme and the token. I've never seen any type of server require a dash as you've shown, and most if not all would send back an error if provided one. – Raman Dec 08 '17 at 21:37
8

Instead of calling axios.get function Use:

axios({ method: 'get', url: 'your URL', headers: { Authorization: `Bearer ${token}` } })
falsarella
  • 12,217
  • 9
  • 69
  • 115
Deepak
  • 724
  • 4
  • 13
  • 1
    this helped me realised i put the body into the config. what a rookie mistake. thanks – Nate Apr 16 '22 at 00:32
4
const response=await axios(url,
    method:"GET"
    {
     headers: {
        "Authorization" : `Bearer ${token}`
      }
    })
AL Mahmud
  • 113
  • 2
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Nov 15 '21 at 19:22
3

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
    }
  );
Ashish
  • 63
  • 5
2

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)
paichato
  • 138
  • 7
0

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

Stefan Becker
  • 5,695
  • 9
  • 20
  • 30
  • 3
    this is for node servers, not for axios – Marc Garcia Jan 15 '20 at 14:57
  • Users finding this question can find this answer useful. This question can be used for working with node servers in use cases, and be a reminderthat cors can solve their issue, or to move their backend header check below the above code. Helped save me so much frustration, Thank you ringing-bell. – DORRITO Jun 16 '20 at 08:54
0

This is the Postman way of doing it:

headers: {
    'Authorization': `Basic ${Buffer.from('username:password').toString('base64')}`
}
Abdalla Roda
  • 607
  • 1
  • 6
  • 13
-1
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!

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
MESDOUR
  • 19
  • 4