2

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

enter image description here

1
  • you are trying to do client-side auth, have you read the docs for it? Commented May 26, 2019 at 7:45

3 Answers 3

5

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
   } 
})
Sign up to request clarification or add additional context in comments.

1 Comment

@Ravisara awesome. Did that make your feature work?
3

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.

pant endpoint 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

2

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

If it is the API, then there is no other option, my answer is in general.
and the question specifically says, he gets 401. I don't know how session storage and cookies have to do with that.
ok, this's just an opinion, as it doesn't answer the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.