joshk132
joshk132

Reputation: 1113

Not getting auth headers when setting axios default

I am trying to send an auth header along with an axios POST request from inside a Vue application. I currently am getting a 401 from my back end with an auth header that works when I do a curl.

I've tried splitting it up into variables and putting it in but that did not work and resulted in the same error (401).

This is just the axios code I am trying to get to work. I have checked with console.log and all values I am trying to send exist, though I don't know how to check the axios headers before sending.

axios.defaults.headers.common["Authorization"] = JWTtoken;
axios.post(updateURL, {
  token: result.token
});

The backend code can't be changed easily for testing so need to figure out why not sending from the front end

I'd like it to send the correct header along with my request so I don't get a 401 status code.

Upvotes: 3

Views: 2921

Answers (2)

Ashraf Sada
Ashraf Sada

Reputation: 4905

Another way by using Axios globals to set for example X-Auth-Token encoding from JWT.io directly like this:

axios.defaults.headers.common["X-Auth-Token"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";

Upvotes: 0

Irfandy J.
Irfandy J.

Reputation: 1464

I think you need this..

axios.defaults.headers.common["Authorization"] = "Bearer " + JWTtoken;
axios.post(updateURL, {
  token: result.token
});

Notice that I add Bearer in the Authorization. It is how JWT was meant to be used according to their introduction.

However, if the answer is wrong. Help us by providing more information about your response in Developer Console as @RuChernChong suggest. Any error logs would be helpful as well.

Upvotes: 1

Related Questions