DEV Community

Discussion on: Fetch in react js returns 401 (unauthorized) while passing access token

Collapse
 
tqbit profile image
tq-bit • Edited

In your fetch request in useFetch, you are directly assigning headers as a second function parameter to the fetch method.

Try and rewrite your useFetch - function to assign the headers to the options object and pass this into the fetch() - function.

If that won't work, please state what backend you're using. For reference, you can also check MDN

const useFetch = (url, headers) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  // Assign headers to options object
  const options = { headers: headers }
    useEffect(async () => {
      // Pass options as second argument instead of headers
      const response = await fetch(url,options)
      const data = await response.json()
      // console.log(data)
      setData(data)
      setLoading(false)
    },[]);
    return {data, loading};
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
saiavinashiitr profile image
Sai Avinash Duddupudi • Edited

Tried it. Facing the same issue again. Please refer below screenshot

i.imgur.com/07swAGc.png

Also, I do not have control over the backend API's

Collapse
 
saiavinashiitr profile image
Sai Avinash Duddupudi • Edited

Hey. I am not directly assigning headers as second param in useFetch. If you observe api_headers it contains headers, method, etc.... have you misunderstood this? My bad, I shouldn't have named the second param as headers

Below is api_headers which I am passing which again consists of headers, method etc...

var api_headers={ method: 'GET',
  headers: {'Authorization': `Bearer ${token.access_token}`,
  "Access-Control-Allow-Origin" : "*", 
  "Access-Control-Allow-Credentials" : true },
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tqbit profile image
tq-bit

Ye, that slipped my attention, my apologies.
The rest of your code doesn't look suspicious. Since you're storing the token in your state, you could try and instead save it as a clientside cookie, explicitly sending it to your backend. Else, I'd see for the backend documentation or verify error logs, if available.