Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

293
Visualizações
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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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
about 4 years ago · Juan Pablo Isaza Relatório

0

Yes, Mandip Giri's answer would work.

Though for convenience sake I would suggest creating file src/utility/axiosInstance.js or something equivalent with contents like this:

import axios from 'axios';

export const axiosInstance = axios.create({
  baseURL: 'https://example.com',
});

export const setToken = (token) => {
  const auth = `Bearer ${token}`;
  axiosInstance.defaults.headers.common['Authorization'] = auth;
};

Than you import axiosInstance and setToken method into whatever component you need and use accordingly to the requirements.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda