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?
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.
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.
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.
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"
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With