Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I send JWT token in axios GET request? [duplicate]

Tags:

I'm new to Vue.js and want to make a request in a component to a restricted api:

  computed: {     token () {       return this.$store.getters.getToken;      },    ...  created () {          axios         .get( this.BASE_URL + '/profile/me')         .then( res => {                     this.profile = res.data;                     console.log('profile is:', res.data);            })           .catch(error => console.log(error))                 }, 

The problem is that I don't know how to include the token into the request header. So not surprisingly I get 401 error in response.

And when I try

axios.defaults.headers.common['Authorization'] = this.token; 

before the get request I receive OPTIONS /profile/me instead of GET /profile/me in the server logs.

How can I fix it?

like image 644
Babr Avatar asked Sep 12 '18 09:09

Babr


People also ask

How do you add a JWT token in Axios request?

To send JSON web token (JWT) in an Axios GET request, we can add it to the headers. to call axios. get with the url and config . In config , we add the headers by setting the headers property to an object that has the Authorization header set to the token value.

Can we send JWT token in GET request?

Use authorization headers for your JWT bearer tokens. Note: JWT is simply a standardized way of sending information between parties, and it is possible that you could safely send a JWT via a URL in other scenarios (e.g. single-use tokens), but it is not something we recommend in the context of Auth0.

How do I send a JWT token from react?

npx create-react-app react-jwt-auth After creating the project, we should set the scene for implementing JWT authentication to our application, we need: Router to implement pages, we will use react-router for this, Login page which we will get user information and send login request to set JWT token.


2 Answers

Axios get() request accept two parameter. So, beside the url, you can also put JWT in it.

axios.get(yourURL, yourConfig) .then(...) 

In your case yourConfig might be something like this

yourConfig = {    headers: {       Authorization: "Bearer " + yourJWTToken    } } 

Also you can read about what you can put in your config here https://github.com/axios/axios. Just search for "Request Config"

like image 176
Lê Quang Bảo Avatar answered Sep 21 '22 18:09

Lê Quang Bảo


This works for me, try like -

let JWTToken = 'xxyyzz';  axios     .get(this.BASE_URL + '/profile/me', { headers: {"Authorization" : `Bearer ${JWTToken}`} })     .then(res => {        this.profile = res.data;        console.log('profile is:', res.data);       })       .catch(error => console.log(error))  
like image 28
Praveen Poonia Avatar answered Sep 24 '22 18:09

Praveen Poonia