简体   繁体   English

在 React Native 中使用 Fetch 将令牌传递给 Django Rest API

[英]Passing Token Using Fetch to a Django Rest API in React Native

I have my rest-api set up in Django and am using React Native to connect with it.我在 Django 中设置了我的 rest-api 并使用 React Native 与之连接。 I have registered users and am able to generate tokens however I am unable to pass the token in the header of the GET request.我已经注册了用户并且能够生成令牌,但是我无法在 GET 请求的标头中传递令牌。 My code is as follows:我的代码如下:

try{
        let response = await fetch("http://127.0.0.1:8000/fishes/auth/",
          {
          method: 'GET',
          headers: {
          //  'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': ' Token '+accessToken,
          }});

        let res = await response.text(); 
}}

I have been following this link http://cheng.logdown.com/posts/2015/10/27/how-to-use-django-rest-frameworks-token-based-authentication and have already verified that the response from the rest api is correct.我一直在关注这个链接http://cheng.logdown.com/posts/2015/10/27/how-to-use-django-rest-frameworks-token-based-authentication并且已经验证了来自休息api是正确的。

However on the phone with native react I get the following error in the console:但是,在具有本机反应的电话上,我在控制台中收到以下错误:

TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (fetch.js:441)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:542)

What am I doing wrong in the GET code?我在 GET 代码中做错了什么?

Alright 401 status code which means UnAuthorized.好的 401 状态代码,这意味着未授权。 For Django Rest Framework you must pass in the access Token as part of header for all your API requests.对于 Django Rest Framework,您必须将访问令牌作为所有 API 请求的标头的一部分传递。

Header Format will be标题格式将是

Key : Authorization
Value:  Token <token>

You can see more here http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication你可以在这里看到更多http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

I think that you need change我认为你需要改变

'Content-Type' to 'content-type' “内容类型”到“内容类型”

On lowercase小写

See This answer .请参阅此答案

The same-origin policy restricts the kinds of requests that a Web page can send to resources from another origin.同源策略限制了网页可以发送到来自另一个源的资源的请求类型。

In the no-cors mode, the browser is limited to sending “simple” requests — those with safelisted methods and safelisted headers only.在 no-cors 模式下,浏览器仅限于发送“简单”请求——仅那些具有安全列表方法和安全列表标头的请求。

To send a cross-origin request with headers like Authorization and X-My-Custom-Header, you have to drop the no-cors mode and support preflight requests (OPTIONS).要发送带有 Authorization 和 X-My-Custom-Header 等标头的跨域请求,您必须放弃 no-cors 模式并支持预检请求 (OPTIONS)。

The distinction between “simple” and “non-simple” requests is for historical reasons. “简单”和“非简单”请求之间的区别是出于历史原因。 Web pages could always perform some cross-origin requests through various means (such as creating and submitting a form), so when Web browsers introduced a principled means of sending cross-origin requests (cross-origin resource sharing, or CORS), it was decided that such “simple” requests could be exempt from the preflight OPTIONS check.网页总是可以通过各种方式(例如创建和提交表单)来执行一些跨域请求,因此当 Web 浏览器引入了发送跨域请求的原则性方式(跨域资源共享,或 CORS)时,决定这种“简单”的请求可以免于预检选项检查。

I got around this issue by handling preflight request, as stated by the OP.正如 OP 所述,我通过处理预检请求解决了这个问题。

Previously, in my middleware, I filtered out requests that did not include an auth token and return 403 if they were trying to access private data.以前,在我的中间件中,我过滤掉了不包含身份验证令牌的请求,如果他们试图访问私有数据,则返回 403。 Now, I check for preflight and send a response allowing these types of headers.现在,我检查预检并发送允许这些类型的标头的响应。 This way, when the following request comes (get, post, etc), it will have the desired headers and I can use my middleware as originally intended.这样,当以下请求出现时(get、post 等),它将具有所需的标头,并且我可以按照最初的预期使用我的中间件。

Here is my middleware:这是我的中间件:

class ValidateInflight(MiddlewareMixin):

def process_view(self, request, view_func, view_args, view_kwargs):
    assert hasattr(request, 'user')
    path = request.path.lstrip('/')

    if path not in EXEMPT_URLS:
        logger.info(path)
        header_token = request.META.get('HTTP_AUTHORIZATION', None)
        if header_token is not None:
            try:
                token = header_token
                token_obj = Token.objects.get(token=token)
                request.user = token_obj.user
            except Token.DoesNotExist:
                return HttpResponse(status=403)
        elif request.method == 'OPTIONS':
            pass
        else:
            return HttpResponse(status=403)

Here is my Options handling这是我的选项处理

class BaseView(View):
 def options(self, request, *args, **kwargs):
     res = super().options(request, *args, **kwargs)
     res['Access-Control-Allow-Origin'] = '*'
     res['Access-Control-Allow-Headers'] = '*'
     return res

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

相关问题 如何从 Django rest 框架使用 Z38C3787939C7D28B86C7 框架从 React Native 中的 api 获取数据 - How to fetch data from an api in React Native from Django rest framework using axios 如何通过Django Rest API本机反应中的标头传递JWT令牌? - How to pass JWT token through header in react native to django rest api? 如何将 React Native 与 django rest api 连接 - How to connect React native with django rest api Django REST API和React Native中的登录和身份验证功能 - Login and authentication functionality in Django REST API and React Native 无法连接到 django rest api 反应 native.network 错误 - Cannot connect to django rest api with react native network error 使用Django rest API验证登录并响应本机前端 - Verify login with Django rest API and react native front end 如何将 REST Api react native + django 应用程序放在 Google Play 上? - How to put a REST Api react native + django application on google play? 正文未发布在 Django Rest API 调用中使用 Z9E13B69D1D2DA927102ACAAAFZ715 - Body not Posting in Django Rest API call using Javascript fetch 使用Javascript访问Django Rest Framework API-获取令牌 - Access Django Rest Framework API using Javascript - getting a Token 通过令牌身份验证使用 django rest 框架创建登录 api 的步骤 - Steps for Creating Login api using django rest framework by Token Authentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM