keijop
keijop

Reputation: 111

Request Authorization header not set - React/Axios

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)
  }
}

Upvotes: 2

Views: 7870

Answers (1)

Hamza Sabljakovic
Hamza Sabljakovic

Reputation: 239

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.

Upvotes: 3

Related Questions