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

420
Visualizações
Fetch : authentication credentials were not provided

When I request this, everything is ok and I get the data:

const get_players = async()=>{
    const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/')
    const data     = await response.json()
    console.log(data)
}    

But when I put permission_classes in views.py, I recive this in the console:

{detail: 'Authentication credentials were not provided.}

I am a beginner in Javascript so I wll hope you can understand.
I dont know how to put the authentication credentials in my fech.

Views.py

class PlayersView(ModelViewSet):             
        permission_classes = [IsAuthenticated]
        serializer_class = PlayersSerializer
        queryset         = Players.objects.all()

    def list(self, request):
        queryset   = Players.objects.all()
        serializer = PlayersSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset   = Players.objects.all()
        qs         = get_object_or_404(queryset, pk=pk)
        serializer = PlayersSerializer(qs)
        return Response(serializer.data) 

Urls.py

router = DefaultRouter()
router.register('players',views.PlayersView,basename='players') 

app_name = 'main'
urlpatterns = [    
    path('',include(router.urls)),           
]

Any idea?

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

0

your view class tell us that you cant access this page unless the user is authenticated (logged in), i suggest in case you are using django default auth (session auth) getting the cookie that stored in local storage like this : localStorage.getItem('csrf') and then set the session id: localStorage.setItem('session_id',res.data.session_id)(this is just a dummy example, i have no idea how you set your session id in the backend) when you receive a response in the frontend, or if you are using token auth (like jwt), you should add to headers : headers: {'Authorization': Token ${apiToken}} , one of the great jwt modules for drf and that easy to use with different endpoints is drf-simplejwt, more info: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/

on a side note : i would not suggest using django default authentication, since it is hard to deal with, especially on the frontend side

about 4 years ago · Juan Pablo Isaza Relatório

0

The user behind the browser that runs the fetch needs to be authenticated, ie. logged in. There are multiple ways to do it. Refer to:

https://www.django-rest-framework.org/api-guide/authentication/

But basically, SessionAuthentication will use Django's user login system, and if you want access the API without logging in, you can use TokenAuthentication in which case, you need to add an HTTP header to your fetch request.

const get_players = async() =>{
    const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/', {
      headers: {
        'Authorization': `Token ${apiToken}`
      }
    })
    const data = await response.json()
    console.log(data)
}
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