irondsd
irondsd

Reputation: 1240

HTTP fetch request always fails on react-native

I have a backend on my server which doesn't have https configured. Before it worked fine with just http and everything was working. For some reason now I'm getting this error:

TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394)
    at XMLHttpRequest.js:507
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:366)
    at MessageQueue.js:106
    at MessageQueue.__guard (MessageQueue.js:314)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)

I googled and it looks like the problem is http. It works fine with https on other apis. But mine doesn't have http configured. Is there a way to make it work with just http for now?

Upvotes: 0

Views: 936

Answers (3)

Iva
Iva

Reputation: 1514

solution one is to add following code to AndroidManifest.xml File

android:usesCleartextTraffic="true"

But in my case I wanted to allow only my API domain So I have added following code to android/app/src/res/xml/network-security-config.xml file.

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="false">localhost</domain>
        <domain includeSubdomains="false">Your IP/Domain</domain>
    </domain-config>

</network-security-config>

I hope this is helpful. Thank you!

Upvotes: 0

irondsd
irondsd

Reputation: 1240

Okay. With a hint of romin21, I made it working now. There's a file

android/app/src/debug/res/xml/react_native_config.xml

that overwrites your AndroidManifest. So at first I tried adding it to AndroidManifest and of course it didn't work, I already had this file overwriting it. But when I added my backend's ip address to that file, it worked perfectly

<domain includeSubdomains="false">YOUR IP</domain>

Upvotes: 1

romin21
romin21

Reputation: 1651

If you're testing on Android, you need to enable clearTextTraffic so the system allows your app to communicate through HTTP.

In your AndroidManifest.xml add android:usesCleartextTraffic="true".

Upvotes: 1

Related Questions