1

I'm developing a mobile app with React Native, and have a REST API in Django at the backend. I want to make a POST request from the app to my API.

Code

function sendDpi() {
const requestOptions = {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    dpi: imageDpi,
  }),
};
fetch('http://127.0.0.1:8000/', requestOptions)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    console.log(error);
  });
}

When sendDpi() is called by my app, I get [TypeError: Network request failed].
127.0.0.1:8000 is where my Django app is running. I've tried using my IP address (as pointed out by this answer) as well.
I've also modified android/app/src/main/AndroidManifest.xml to include android:usesCleartextTraffic="true".

3 Answers 3

2

The suggestion made before was great except the URL needed should be http://10.0.2.2:8000 instead of http://10.0.2.2/8000

Sign up to request clarification or add additional context in comments.

Comments

2

I think 127.0.0.1:8000 is also localhost. You need to find your external ip address if you use a physical device to test from.

I you test from android emulator you can just use http://10.0.2.2/8000.

Also try to make it work with http first. You might not have a valid SSL certificate. With invalid SSL certificate you also get [TypeError: Network request failed]

4 Comments

I get the same error when I use 10.0.2.2/8000 or my external IP address. What did you mean by 'make it work with HTTP first'?
If your Django app is serving ‘https://‘ and you don’t have a valid ssl certificate then you’ll will get the error. Can the Django app serve as ‘http://‘?
yeah, it can serve as 'http://'
@protonpasta you still have the problem? Could it be a firewall problem? You could try to serve your django app through ngrok: twilio.com/blog/….
0

In Django settings.py

ALLOWED_HOSTS = ['192.168.1.7']

Starting Django shell

python manage.py runserver 192.168.1.7:8000

Check link on browser if working

http://192.168.1.7:8000/polls/articles/

In React/ReactNative project, see result on shell

useEffect(() => {
        fetch('http://192.168.1.7:8000/polls/articles/',
        {method: 'GET'})
        .then(resp => resp.json())
        .then(data => {
            console.log(data)
        })
        .catch(error => console.log(error))
    }, [])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.