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

188
Visualizações
How to access a Django rest Framework API from React

I started to use django recently and I also tried to use React js and I wanted to do something simple like a nav var in React. I have accounts and log in implemented using django forms which work well. For the nav I would need to fetch the user information which I have on a DRF API as follows in the views file:

@api_view(['GET'])
@authentication_classes((SessionAuthentication, TokenAuthentication))
@ensure_csrf_cookie
@permission_classes((IsAuthenticated,))
def user_details_view(request, *args, **kwargs): #REST API for detailing some basic info about the user that is using the system at the moment
    current_user = request.user
    id = current_user.id
    status = 200
    try:
        obj = CustomUser.objects.get(id=id)
        data = UserSerializer(obj)
        return Response(data.data, status=status)
    except:
        status = 404
        return Response(status=404)
        return Response(data.data, status=status)

The urls are set up and if I access it in the django server it works fine but when I try on react by:

function loadUserInfo(callback){
  const xhr = new XMLHttpRequest();
  const method = 'GET';
  const url = "http://127.0.0.1:8000/userdetails/";
  const responseType = "json";
  xhr.responseType = responseType; // Let the xhr request know that its getting a json 
  xhr.open(method, url); //This opens the request with the method and url entered
  xhr.onload = function(){
    console.log("This is the response: ",xhr.response)
    callback(xhr.response, xhr.status)
  }
  xhr.onerror = function(){
    callback({"message":"The request was an error"}, 400)
  }
  xhr.send();//Trigger that request
}

I get:

GET http://127.0.0.1:8000/userdetails/ 403 (Forbidden)
This is the response:  {detail: 'Authentication credentials were not provided.'}

How can I make React access the data? I only need to have some minor components made by react and also have it so that if I open it on another browser I can log in with a different user. I have looked into many resources but they do not seem to work for my case. I am using the django server.

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

0

You have to get the auth token in your react app. The token is generated once you log in to your Django from react app, and then you need to pass that token along with the get method.

axios
  .get('http://www.exapmle.com', {
    headers: {
      Authorization: `Token ${props.token}`,
    },
  })

or in your Django app set the permission class as any for that model, or remove IsAuthenticated from the permission class.

   permission_classes = [IsAuthenticated]
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