Search code examples
javascriptreactjsdjango-rest-frameworkaxiostoken

How to use token authorization with axios in react.js


I have this function in react.js that should access a django rest framework using a token access:

 getAll(token) {
        axios.defaults.headers.common['Authorization'] = "Token " + token
        return axios.get('http://localhost:8000/api/todos/');

I keep getting:

GET http://localhost:8000/api/todos/ 401 (Unauthorized)

I have tried calling the http request on Insomnia and everything seems fine. the successful curl request from Insomnia is

curl --request GET \
  --url http://127.0.0.1:8000/api/todos \
  --header 'Authorization: Token 9a60ef4a5fbaab1b0fa9c3e8e8a5626b757e148d' \
  --header 'Content-Type: application/json' \
  --cookie csrftoken=MtpItNeHebjs7OaAfTTJBO3x4ezh5FfnVg1mNjOuNTy1piK9DXxSusb4oxW2qy1e

How would I implement this token request using axios in react.js


Solution

  • I think the issue might be

    "Token " + token
    

    I think the rest API is looking for a bearer token as authorization so you might want to use

     axios.defaults.headers.common['Authorization'] = "Bearer " + token