Search code examples
javascriptreact-nativefetch-apidjango-rest-auth

Why is fetch query always returning error segment?


I am using the following code from react-native mobile application to make a social authentication call to dj-rest-auth local link. However I am always receiving an error. Please let me know what is the issue.

  fetch(
    "http://localhost:8000/dj-rest-auth/facebook/",
    {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-type':'application/json'
      },
      xsrfCookieName:"csrftoken",
      xsrfHeaderName:'X-CSRFToken',
      body:JSON.stringify({access_token : resolvedToken})
    }
  )
  .then(resp => resp.json())
  .then(data => {
    console.log(data);
  }  
  )
  .catch(error => console.log(error))

Error Details:

Network request failed
at node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0
at [native code]:null in callFunctionReturnFlushedQueue

Alternate Error Update: If I use axios for the API request instead of fetch i.e. await axios.post instead of fetch, then i am getting the following error:

Network Error
at node_modules/axios/lib/core/createError.js:16:14 in createError
at node_modules/axios/lib/adapters/xhr.js:84:24 in handleError
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:600:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:395:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
at [native code]:null in callFunctionReturnFlushedQueue

Solution

  • The error was being faced due to the usage of localhost address for django local server call here. The issue remains for localhost or 127.0.0.1 as well.

    Also, next I tried using mobile hotspot with my laptop and then used the currently assigned IP address of my laptop's Wi-Fi, to run django server and place API call to it. This doesn't work if using mobile hotspot and same error is faced.

    However upon using a LAN router and then using the assigned local Wi-Fi IP address of the laptop, the issue was resolved.

    This has now created new issue though. The API call succeeds and i receive the token only upon the first API call or first run. Thereafter I receive the error of missing or invalid csrf token.

    However since that is a new issue and is different from this question, I am currently closing this question. If I am unable to resolve the new issue, I may ask a new question.