2

I have jwt user auth token that I am trying to set for the Authorization header to Axios GET request. But it is not set. Backend shows undefined and firefox dev tools don't show any Authorization header set for HTTP request. Same token and same helper function sets the header for POST request and backend reads it correctly.

const setAuthHeader = user => {
  return { headers: { Authorization: `Bearer ${user.token}` } }
}

GET doesn't set header

export const getWeights = async user => {
  try {
    const resp = await axios.get(
      baseUrl,
      { userId: user.id },
      setAuthHeader(user)
    )
    return resp.data
  } catch (error) {
    console.log(`error`, error)
  }
}

POST sets header

export const postWeights = async (user, weight, date) => {
  try {
    const resp = await axios.post(
      baseUrl,
      { userId: user.id, weight, date },
      setAuthHeader(user)
    )
    return resp.data
  } catch (error) {
    console.log(`error`, error)
  }
}

1 Answer 1

3

Axios POST and GET have different method signatures.

axios.post(url[,data[, config]])

axios.get(url[,config])

So if you rewrite your GET method to the following

export const getWeights = async user => {
  try {
    const resp = await axios.get(
      baseUrl,
      setAuthHeader(user)
    )
    return resp.data
  } catch (error) {
    console.log(`error`, error)
  }
}

It will fix the issue. Also, if you need to pass the { userId: user.id } you could use something like this

export const getWeights = async user => {
  try {
    const resp = await axios.get(
      baseUrl,
      { params: { userId: user.id }, headers: { Authorization: `Bearer ${user.token}` }  }
    )
    return resp.data
  } catch (error) {
    console.log(`error`, error)
  }
}

This will result in a request with query params: http://example.com?userId=xxx.

Which may or may not be what you need, there is no way for me to tell without looking at the API. It depends on where the API is expecting to receive the userId parameter, query param, path variable, request body, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Omg what a silly mistake. I was facing a deadline for this school project and coud not see the elephant in the room. Thank you for your help. PS I wrote the API myself so I can easily rewrite the necessary part in backend to get the user id from params.

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.