axios doesn't see request headers that I set

Created on 9 May 2017  ·  58Comments  ·  Source: axios/axios

Hi,

I tried to make a CORS API post call using axios but I've been never able to do that because I must set headers to make a proper call however axios doesn't see the headers I set.

For example,

This is what I set as URL and Headers;

    DASHBOARDS_LIST: {
        URL: "http://10.254.147.184:11103/api/1.0/devices/",
        HEADERS: {
          "Content-Type": "application/json",
          "Authorization": "Bearer 700e9323-0140-4d49-b574-e8652fa433ad"
        }
    }

The request is sent successfully so I don't write the code where I call axios. The problem is I couldn't set the headers.

This is the request pic;

image

This is my axiosConfig;

image

Even if I set "Authorization", I don't know why it is not shown in my request.

Most helpful comment

I'd like to say that I've encountered this error and solved it doing the following:
Instead of doing:
return axios.get(api + '/api/user/getUserInfo', { params: { UserId: 1 } }, config)

Where

config = { headers: { 'Authorization': 'Bearer ' + accessToken } }

I did:

return axios({ method: 'get', url: api + '/api/user/getUserInfo?UserId=1', headers: { 'Authorization': 'Bearer ' + accessToken } })

And it worked. I hope to help someone with this.
Cheers!

All 58 comments

Isn't this just a CORS problem?

You need to add CORS-specific response headers on your server side:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization

I have the same problem, here is my code

axios({ 
                url: '/games/homelist',
                method:'get',
                headers : {
                    Authorization : "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0b3RvIiwiZXhwIjoxNDk1ODI5NDA3fQ.O2xvqz15TwxdKxB0aTxm32ySdrcZjf_fsJB3FdUV1ESwWZ3bW4PKPWgm3RI6SPMeaX6Hh0Bdjirgyp4FkdPeRQ"
                }
            })
            .then((response) => {
                this.gamesInfos = response.data
            })
            .catch(function(error) {
                console.log(error)
            });

My cors configuration is fine as seen below

image

but the Authorization value is not attached to the request. I tried with the global configuration but same problem

Content-Type application/x-www-form-urlencoded #362
A bug opened more than a year...

I am still getting the same problem

POST call is converting to OPTION
I am sending both Authorization and Content-Type application/x-www-form-urlencoded headers using axios . But only authorization header is send in request header. content-type header is missing from axios call

I had this problem too. My server is a rest api written in php. I have added to all comming request these header:
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization');
The last line indicates which headers are allowed. I added Authorization so I can set this header to my client.

Try:

this.app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, access-control-allow-origin, profilerefid(whatever header you need)");
next();
});

Some comments here indicate that this is a CORS issue from the server side, yet I can submit the same request perfectly using a different client in Python, sending the same authorization header and same data.

Yet it will not work with Axios.

I'd like to say that I've encountered this error and solved it doing the following:
Instead of doing:
return axios.get(api + '/api/user/getUserInfo', { params: { UserId: 1 } }, config)

Where

config = { headers: { 'Authorization': 'Bearer ' + accessToken } }

I did:

return axios({ method: 'get', url: api + '/api/user/getUserInfo?UserId=1', headers: { 'Authorization': 'Bearer ' + accessToken } })

And it worked. I hope to help someone with this.
Cheers!

@pedro-rates Thanks, this worked for me as well! Anyone have a clue why the method alias won't work?

let out = []; for (let key in this.Data) { // in my case it is props: { Data: {} }, out.push(key + '=' + encodeURIComponent(thisUI.Data[key])); } this.$root.axios({method: 'POST', data: out.join('&')}).then(function (response) {......

it's the stupidest solution... but it's work for me and my CORS requests....

I have the same problem and @pedro-rates solution didn't fix it. :(

Can someone post a clear snippet of code that reproduces this issue? Never seen this in axios before.
instead of passing the Authorization header and api url with every request, why not pass it as default config

var instance = axios.create({
  baseURL: 'http://exampleapi.com/',
  headers: {'Authorization': 'Bearer ksdjfglksgflksgsjdhglaslfkhgasf'}
})

instance.get('user').then(response => ....)

@Khaledgarbaya This alias method does not work with Authorization header

var config = {
    headers: { 'Authorization': 'Bearer ksdjfglksgflksgsjdhglaslfkhgasf' }
}

return axios.get(url, data, config)

But this way, it does work

return axios({
    method: 'get',
    url: url,
    headers: { 'Authorization': 'Bearer ' + accessToken }
})

@dmitrij-onoffapp get fundtion does not accept data object

var config = {
    headers: { 'Authorization': 'Bearer ksdjfglksgflksgsjdhglaslfkhgasf' }
}

return axios.get(url, config)

@dmitrij-onoffapp Thank you! That worked great!

@Khaledgarbaya

var api = axios.create({ baseURL: '<host>', timeout: 10000, transformRequest: [(data) => data], headers: { 'Accept': 'application/json,*/*', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Authorization', 'Authorization': 'Bearer ' + token } })

api.post('/rooms') ... and no Authorization header

2018-02-24 23 13 21

Same issue here with delete request

I've added OPTIONS to Access-Control-Allow-Headers, and it works well :D

@Khaledgarbaya still an issue.

axios.put(url, {headers: headers, params: params}) //headers are not sent

Thanks @dmitrij-onoffapp for providing the workaround
axios({method: 'put', url: url, headers: headers, params: params}) //headers are sent

Tested on Axios 0.18.0

Works like this as well:

const authString = 'Bearer '.concat(AccessToken);

requestData = {
                'DeviceId':  dataStuff,
                'ParameterId': moreData
            }
const variableIdResponse = await axios({
                method: 'post',
                url: variableIdURL,
                data: requestData,  
                headers: { 'Authorization': authString }
            });

I'm having the same experience with setting headers. Headers are set when using

axios({method: 'post' ...

but not when using

axios.post({ ...

I also have some issues,

after I received the JWT token.

then I set using axios.defaults.headers.common["Authorization"] = 'Bearer '+ constants.token;

but after I try to axios.post('api/logout') it returns an error. and it turns out that the Authorization Header is not there.

Is there any way that I made it wrong? Or do I have to just add the Auth header every now and then?

Only one remark to the client/server aspect:

A possible factor for a missing "Authenticaton" header from axios
may in fact be the CORS headers sent by the server.
The server only sets the headers and does nothing more.
It depends on the client implementation how the client reacts to them.

So in order to not swallow, but actually send the “Authentication”-header,
axios looks, if the server sends the right “Allow”-Headers in it's response.

e.g. a not sufficient CORS header on server side would be:
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept”
(note: the word "Authorization" is missing here!)

The server needs to explicitly allow the “Authorization” header lke so:
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization”

So the full CORS headers could look something like this:
Access-Control-Allow-Origin: "*"
Access-Control-Allow-Methods: "DELETE, GET, OPTIONS, PATCH, POST, PUT"
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization”

If “Authorization” is missing in the header on the server side,
then axios already detects this in its “preflight” request and then
does not send the authorizaton header at all.

Other clients may have different implementations and do not correctly listen
to the CORS-headers sent from the server. They then just send everything
including the authorization header without regards to what the server tells
them. (In other words: they are not working correctly.)

So then it might look, like axios is wrong. But in fact it really isn’t 😉

This problem still exists. The solution is as per @jsve mentioned.
Is there a plan to actually fix it, or not?

In my case it's definitely NOT a CORS issue. And axios is clearly wrong if it works with one method of usage and not with another.

@Khaledgarbaya that was it! I copy and pasted axios.post(url, {}, headers) and changed it to axios.get, but GET is not supposed to send payload. I got rid of the empty payload object and now axios.get(url, headers) works fine for me.

Hi all ,
this problem is still existing ,
I am using React + Express + Axios
My CORS in server is added below

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", clientURL);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
// res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
next();
});
=================================== react app - client side ========================
var config = {
headers: {
'Authorization': 'Basic YXBwbGljYXRpb246c2VjcmV0',
'Content-Type': 'application/x-www-form-urlencoded'
}
}
// Axios.defaults.headers.common['Authorization'] = 'Basic YXBwbGljYXRpb246c2VjcmV0';
// Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// Axios.defaults.headers.common['Authorization'] = "Basic YXBwbGljYXRpb246c2VjcmV0"
Axios.post('/oauth/token', params, config).then((response) => {

  if (response.status === 200) {
   alert("request reached in server");
}
).catch((error) => {
  console.log(error);
 alert.error('Oops some error occured please check the data you have submitted');
});

============================== End React side =================================
screenshot from 2018-12-07 13-07-59
Note : if i remove the Authorization header request header will set properly
Quick response will be appreciated almost spend a day with this
Thanks in advance
-anoop

@dmitrij-onoffapp get fundtion does not accept data object

var config = {
    headers: { 'Authorization': 'Bearer ksdjfglksgflksgsjdhglaslfkhgasf' }
}

return axios.get(url, config)

This was the trick. I was setting the data object, thinking the api would be the same as for post requests..
Guess its not a bug but rather bad interpretation/reading of the api.

@RickVM this is not the same issue that most people are experiencing. See below.

@anoop-kk @roynes have you tried the workaround outlined in the comments above? (reproduced below for convenience)

Reposting workaround for those still having issues with Authorization header not appearing despite being set. Thanks dmitrij-onoffapp for providing the workaround

axios.put(url, {headers: headers, params: params}) //'authorization' header not sent
axios({method: 'put', url: url, headers: headers, params: params}) //'authorization' header sent

(previously tested on Axios 0.18.0)

in my code Authorization is not sending. I get the response status 403. attach my code
var data =new FormData() data.append('userId',this.state.UserID); data.append('new_password',this.state.password); data.append('confirm_password',this.state.confirm_password); var config = { headers:{'Authorization':this.state.UserToken} } Axios.post(baseURL,data,config) .then((response)=>{ console.log(response) }).catch((error)=>{ console.log(error) })

@SubashManian please read the comment above yours for the solution.

@SubashManian please read the comment above yours for the solution.

I tried that too.
Authorization is not sent on that method for me. response status:403 for me

@SubashManian +1. I tried doing the solution suggested. It doesn't work for me as well.

+1, facing this problem too.

Reposting workaround for those still having issues with Authorization header not appearing despite being set. Thanks dmitrij-onoffapp for providing the workaround

axios.put(url, {headers: headers, params: params}) //'authorization' header not sent
axios({method: 'put', url: url, headers: headers, params: params}) //'authorization' header sent

(previously tested on Axios 0.18.0)

@arshbhatti8 @bruno-edo if the proposed workaround doesn't fix your issue, then either:
1) your header is not being sent due to CORS (see comments earlier in the thread)
2) there is another issue, in which case please open a new issue with the details

Same issue here!

Update: fixed it by changing the time to set header

@hassan-jahan can you explain your fix? Does the time affects whether axios will send the header or not?

Problem still exists when server set Access-Control-Allow-Headers: *
According https://tools.ietf.org/html/rfc7480

When responding to queries, it is RECOMMENDED that servers use the
Access-Control-Allow-Origin header field, as specified by
[W3C.REC-cors-20140116]. A value of "*" is suitable when RDAP is
used for public resources.

axios 0.18.0

@barmaley443 Can you confirm that you tried the fix listed above and that it did not work for you?

@barmaley443 Can you confirm that you tried the fix listed above and that it did not work for you?

yes. i have always use axios({method: 'put', url: url, headers: headers, params: params}) notation in my project.

when server sent Access-Control-Allow-Headers: *
i receive missing token ‘authorization’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel error in firefox 66.0.5 (64-bit) and Safari

all works fine when server sent Access-Control-Allow-Headers: "Authorization, Content-Type, Range"

@barmaley443 isn't it normal that server needs to set header Access-Control-Allow-Headers: "Authorization" at very least? See comments about CORS at the top of this thread.

i think it's right to see rfc :) https://tools.ietf.org/html/rfc7480

A value of "*" is suitable when RDAP is used for public resources.

* is only allowed for origins, deciding which headers are allowed to be sent is a separate process, and * is not allowed for headers. See https://stackoverflow.com/a/33704645/675721 . The RFC you quote uses it for Access-Control-Allow-Origin, not for Access-Control-Allow-Headers. Refer to the flow in https://www.w3.org/TR/2014/REC-cors-20140116/ . Regardless, if you feel that this is a bug in axios, please open a new issue.

@hassan-jahan can you explain your fix? Does the time affects whether axios will send the header or not?

Actually, I set headers in an interceptor but I had changed axios.defaults.headers.common instead of modifying and returning 'config'. So it was my fault, but the point was that it works for years in one of my projects but doesn't work at all in another one.

* is only allowed for origins, deciding which headers are allowed to be sent is a separate process, and * is not allowed for headers. See https://stackoverflow.com/a/33704645/675721 . The RFC you quote uses it for Access-Control-Allow-Origin, not for Access-Control-Allow-Headers. Refer to the flow in https://www.w3.org/TR/2014/REC-cors-20140116/ . Regardless, if you feel that this is a bug in axios, please open a new issue.

i think you are right at this point. FYI https://github.com/whatwg/fetch/issues/251 https://bugzilla.mozilla.org/show_bug.cgi?id=1309358

@barmaley443 nice. It's hard to keep up with these specs.

Reposting workaround for newcomers...If you're having issues with authorization header not being sent by Axios, please check that you have the correct headers set:

  • Access-Control-Allow-Origin: *, or just your origin.
  • Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD or just the method you're using. * not allowed here.
  • Access-Control-Allow-Headers: Authorization and any other headers you wish to include. * not allowed here. List

If you're still having issues, try using axios({method: yourMethod}) instead of axios.yourMethod().

axios.put(url, {headers: headers, params: params}) //'authorization' header not sent
axios({method: 'put', url: url, headers: headers, params: params}) //'authorization' header sent

If none of these fixes your issue, please open a new one.
@emilyemorehouse @mzabriskie @nickuraltsev @rubennorte please consider locking comments on this issue.

For those running into this problem on Brave Browser, try turning off the "Shields" (its built-in AdBlock). I lost many hours trying all solutions possible and, in the end, was the blocker editing the headers.

I'd like to say that I've encountered this error and solved it doing the following:
Instead of doing:
return axios.get(api + '/api/user/getUserInfo', { params: { UserId: 1 } }, config)

Where

config = { headers: { 'Authorization': 'Bearer ' + accessToken } }

I did:

return axios({ method: 'get', url: api + '/api/user/getUserInfo?UserId=1', headers: { 'Authorization': 'Bearer ' + accessToken } })

And it worked. I hope to help someone with this.
Cheers!

This worked for me! THANK YOU!

Reposting workaround so it doesn't get lost in thread.

If you're having issues with authorization header not being sent by Axios, please check that you have the correct headers set:

  • Access-Control-Allow-Origin: *, or just your origin.
  • Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD or just the method you're using. * not allowed here.
  • Access-Control-Allow-Headers: Authorization and any other headers you wish to include. * not allowed here. List

If you're still having issues, try using axios({method: yourMethod}) instead of axios.yourMethod().

axios.put(url, {headers: headers, params: params}) //'authorization' header not sent
axios({method: 'put', url: url, headers: headers, params: params}) //'authorization' header sent

If none of these fixes your issue, please open a new one.

@Khaledgarbaya This alias method does not work with Authorization header

var config = {
    headers: { 'Authorization': 'Bearer ksdjfglksgflksgsjdhglaslfkhgasf' }
}

return axios.get(url, data, config)

But this way, it does work

return axios({
    method: 'get',
    url: url,
    headers: { 'Authorization': 'Bearer ' + accessToken }
})

⬆︎⬆︎⬆︎⬆︎⬆︎⬆︎ THIS. Three whole nights playing with .htaccess on Apache server, CORS, headers. And it was this. THANK YOU.

This bug is very frustrating. It appeared in a React Native project I was working on. Hunted it for weeks. On some devices the header was attached and on some it wasn't. Android always worked, some iPhones were failing. Even the same device sometimes started working without any explanation. In the end that's what worked:

axios.put(url, {headers: headers, params: params}) //'authorization' header not sent
axios({method: 'put', url: url, headers: headers, params: params}) //'authorization' header sent

I had to modify ~30 calls through the whole application.

I do not blame axios. The bug is first reported in 2017. Obviously it appears in some environments and it doesn't appear in others. Well, the usual UFO in the world of software development, I guess.

In some environment axios don't see the header. We can fix this issue from back-end side No need to do anything from front-end side.
While downloading pdf file from any browser I unable to see Content-Disposition header. Used below code to resolve this issue.

httpServletResponse.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
httpServletResponse.setHeader(Content-Disposition,xyz.pdf);

In some environment axios don't see the header. We can fix this issue from back-end side No need to do anything from front-end side.

just download this package: https://www.npmjs.com/package/cors
and added to your application.

node Js

I had the same problem, and my problem was combined:
1 - In my Koa server, I have already used the cors() middleware, but I had it AFTER the authentication middleware, so my headers weren't allowed when needed. I moved it to the top of the middleware chain.
2 - In my app, I have used axios.create() to simplify the process of requests, but as I understood from the comments, It has problem in some cases. I used a lot of different things like trying to change axios defaults, or creating a global config object which I can pass to axios request as config every time, so I don't have to write the defaults manually every time, but none of them worked. Then I found out that I have to prevent using axios.methodName, and I have to write the config object for every request explicitly, like this:

axios('My URL', {
  method: 'METHOD',
  baseURL: 'Base URL',
  headers: {
    // ...
  }
})

And it works! I think the only thing that doesn't work with axios.defaults or axios instances is the headers property, but I'm not sure. By the way, hope it helps someone!

I had the same issue.
This Issues https://github.com/axios/axios/issues/969 helped me resolve the problem.

Ideally, the Axios post expects to have data passed as a parameter. Therefore, if you only pass URL and headers, the headers are treated as data. Pass a null option if you don't have data to pass to the post request.

axios.post(url, null, headers)

I'm now doubting if I need to use the Delete method to logout instead of the Post Method.

Reposting summary of solutions & workarounds so they doesn't get lost in thread.

TL;DR

Use axios({method: yourMethod}) instead of axios.yourMethod().

axios.put(url, {headers: headers, params: params}) //'authorization' header not sent
axios({method: 'put', url: url, headers: headers, params: params}) //'authorization' header sent

Method signature reminder (comment)

Reminder: Don't forget that the signature for axios.post, .put and .patch requires data as the second parameter, so trying to put headers as the second parameter will cause them to be sent as POST data, not as headers.

axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

CORS

If you're still having issues with authorization header not being sent by Axios, please check that you have the correct headers set:

  • Access-Control-Allow-Origin: *, or just your origin.
  • Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD or just the method you're using. * not allowed here.
  • Access-Control-Allow-Headers: Authorization and any other headers you wish to include. * not allowed here. List

Still not working?

If none of these fixes your problem, please open a new issue. Your problem is unrelated to this issue, DO NOT post in this issue.

I solved my issue using:
Axios.get(url,header,params) => Axios.get('http://localhost/api/', {headers: {'Authorization':'Token ' + tokenhere} }, params)

my code before w/c was not working was these format:
Axios.get(url, params,header) => Axios.get('http://localhost/api/', params, {headers: {'Authorization':'Token ' + tokenhere} })

Nothing here worked, but there's a final way to get around this that worked for me:

let token = 'xxx';
let params = { // your params here, with headers
  headers: {
    Authorization: "Bearer "  + token
  }
};

// this forces headers:
params.transformRequest = [
    function (data, headers) {
        for (let i in params.headers) {
            headers[i] = params.headers[i];
        }
        return data;
    }
];

This worked for me when the other solutions failed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

j-planet picture j-planet  ·  70Comments

kalaspuffar picture kalaspuffar  ·  36Comments

benjamingeorge picture benjamingeorge  ·  48Comments

jiimmeh picture jiimmeh  ·  87Comments

kyeotic picture kyeotic  ·  64Comments