There is 401 error(Invalid or not provided access token), How to pass token correctly with axios, This is my code & API documentation: https://trefle.io
3 Answers
It all depends on how your API is setup to consume the token. Generally speaking though you can pass in a token through the headers property in axios.
axios.get("https://trefle.io//api/plants/${id}", {
headers: {
Authorization : yourtoken
}
})
1 Comment
Cat_Enthusiast
@Ravisara awesome. Did that make your feature work?
From trefle docs, you first need to request a client-side token which will return JWT token, that'll be used to make requests from client side.
// requst JWT token
https://trefle.io/api/auth/claim?token=YOUR-TOKEN&origin=YOUR-WEBSITE-URL
The plant endpoint accepts two params, id path parameter and token query parameter.
You need to pass your token as a query parameter.
componentDidMount = () => {
axios.get('https://trefle.io/api/plants/103505?token=YOURTOKEN')
.then(res => {
console.log(res)
})
.catch(e => console.log(e))
}
or
componentDidMount = () => {
axios.get('https://trefle.io/api/plants/103505', {
params: {
token: 'YOURTOKEN'
}
})
.then(res => {
console.log(res)
})
.catch(e => console.log(e))
}
Comments
It depends how you have organized your code/architecture.
- You can store the token in session or local storages, but each time you make a call you need to pass the token through the headers each time OR you can create an interceptor which will handle that for you.
- You can store the token in the cookie as well. This is good if you are running you React app with node using server-side rendering (SSR). In this case you don't need to do something, as cookie are being send through headers automatically.
- You can also store the token in a session, but in case you care about auto-scaling, you need to use Redis and not a memory storage, so token will be available for all the instances your app is running on.
Small note - don't send the token through query params.
3 Comments
Hayk Aghabekyan
If it is the API, then there is no other option, my answer is in general.
Junius L
and the question specifically says, he gets 401. I don't know how session storage and cookies have to do with that.
Junius L
ok, this's just an opinion, as it doesn't answer the question?
