1
votes

I build a Django API using django rest framework. And a want to access the json response data of the api in my react-native app. But a get an error (Network request failed)

DJANGO RESPONSE enter image description here

REACT-NATIVE enter image description here

ERROR

Network request failed

  • node_modules/whatwg-fetch/dist/fetch.umd.js:505:17 in setTimeout$argument_0
  • node_modules/react-native/Libraries/Core/Timers/JSTimers.js:135:14 in _callTimer
  • node_modules/react-native/Libraries/Core/Timers/JSTimers.js:387:16 in callTimers
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
  • [native code]:null in callFunctionReturnFlushedQueue
1

1 Answers

2
votes

Please consider take the following suggestions:

  1. activate developer mode on your device and than turn on the "USB Debugging" mode.

  2. Plug your device into a USB port on your pc

  3. Add this line into your package.json file inside the scripts object:

    "android-dev": "adb reverse tcp:8081 tcp:8081"

  4. Check if CORS is configured in your settings.py Django project file and make sure to allow all hosts to access the project (of specify the hosts if that's important to your tests).

    INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ... ]

    MIDDLEWARE = [
    ...
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
    ]
    
    CORS_ORIGIN_ALLOW_ALL = True
    ALLOWED_HOSTS = ['*']
    
  5. Check your local ip (usually starts with 192.168...). Do this by running ipconfig on windows or ifconfig on linux.

  6. Make sure you are running your Django project with the same IP as your local network. For exemple, my local ip is 192.168.15.2, so I run python manage.py runserver 192.168.15.2:8000. In my case I like to use Pycharm, so I configure it in the server settings enter image description here

  7. And for the last step, use that same IP in your requests adding the "Access-Control-Allow-Origin":'*' in the request header. So it would be something like this:

enter image description here

Note that I use axios for sending requests, but you can check how add the headers in your request using fetch here.

I wish you the best. This is really a annoying problem that I took some time to figure it out.