Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading