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. 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. 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.

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?


Alright 401 status code which means UnAuthorized. For Django Rest Framework you must pass in the access Token as part of header for all your API requests.

Header Format will be

Key : Authorization
Value:  Token <token>

You can see more here http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication


I think that you need change

'Content-Type' to 'content-type'

On lowercase

链接地址: http://www.djcxy.com/p/33794.html

上一篇: 本地应用休息api社交登录流程

下一篇: 将令牌传递给React Native中的Django Rest API