简体   繁体   English

获取:未提供身份验证凭据

[英]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:但是当我将permission_classes放入 views.py 时,我在控制台中收到了这个:

{detail: 'Authentication credentials were not provided.}

I am a beginner in Javascript so I wll hope you can understand.我是 Javascript 的初学者,希望您能理解。
I dont know how to put the authentication credentials in my fech.我不知道如何将身份验证凭据放在我的 fech 中。

Views.py视图.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网址.py

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

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

Any idea?任何想法?

The user behind the browser that runs the fetch needs to be authenticated, ie.运行 fetch 的浏览器背后的用户需要经过身份验证,即。 logged in. There are multiple ways to do it.登录。有多种方法可以做到这一点。 Refer to:参考:

https://www.django-rest-framework.org/api-guide/authentication/ 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.但基本上, SessionAuthentication将使用 Django 的用户登录系统,如果你想在不登录的情况下访问 API,你可以使用TokenAuthentication在这种情况下,你需要添加一个 HTTP Z099FB995346F31C749F6E40EDB3 到你的获取请求。

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)
}

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/您的观点 class 告诉我们,除非用户经过身份验证(登录),否则您无法访问此页面,我建议您使用 django 默认身份验证(会话身份验证)获取存储在本地存储中的 cookie,如下所示: localStorage.getItem('csrf')然后设置 session id: localStorage.setItem('session_id',res.data.session_id) (这只是一个虚拟的例子,我不知道你是如何设置你的 session id 在后端收到)前端的响应,或者如果您使用令牌身份验证(如 jwt),则应添加到 headers: headers: {'Authorization': Token ${apiToken}} ,用于 drf 的出色 jwt 模块之一,很容易与不同端点一起使用的是drf-simplejwt ,更多信息: 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附带说明:我不建议使用 django 默认身份验证,因为它很难处理,尤其是在前端

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM