react-native: TypeError: Network request failed On Android
Hi Everyone, I found this problem on my React-Native Android App. When I using a fetch to communicate with a working api, this type of error is returned to me.
TypeError: Network request failed
I Used the Chrome debbuger and I found this:
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)
This is the code that I used:
`static creaUtente(identity, FirstName, LastName, FiscalCode , Email) { let formdata = new FormData(); formdata.append(‘Identity’, identity); formdata.append(‘FirstName’, FirstName); formdata.append(‘LastName’, LastName); formdata.append(‘FiscalCode’, FiscalCode); formdata.append(‘Email’, Email);
console.log(Configuration.base_url.rest + Configuration.apiRoutes.signUp)
console.log(formdata)
return new Promise((resolve, reject)=> {
fetch('https://linktotheapi.com',{
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.Error){
Alert.alert("Errore");
}
global.utente = responseData;
resolve(responseData)
})
.catch((err) => {reject(err)})
})
}`
I manually tried to use the API and it works. So the problem is fetch. I have seen and read that a lot have encountered this problem on android without a real solution.
The API link is a link type: https: //****.com (it is not a localhost). I tried to use the http version of the API but the error still appears.
Now, This is my package.json
dependencies": { "@react-native-community/async-storage": "^1.4.2", "buffer": "^5.2.1", "pouchdb-adapter-asyncstorage": "^6.4.1", "pouchdb-authentication": "^1.1.3", "pouchdb-find": "^7.0.0", "pouchdb-react-native": "^6.4.1", "react": "16.8.3", "react-native": "0.59.4", "react-native-ble-manager": "^6.6.2", "react-native-ble-plx": "^1.0.3", "react-native-json-tree": "^1.2.0", "react-native-keyboard-aware-scroll-view": "^0.8.0", "react-native-router-flux": "^4.0.6", "react-native-tab-navigator": "^0.3.4", "react-native-vector-icons": "^6.4.2" }, "devDependencies": { "@babel/core": "7.4.3", "@babel/runtime": "7.4.3", "babel-jest": "24.7.1", "jest": "24.7.1", "metro-react-native-babel-preset": "0.53.1", "react-test-renderer": "16.8.3" }, "jest": { "preset": "react-native" } }
I have read that this problem is on Android Device ( I obviously added internet permissions in the Manifest file ). Do you know nothing about this problem??
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 40
- Comments: 114 (2 by maintainers)
Commits related to this issue
- React Native sync for revisions c28f313...0cac4d5 Summary: This sync includes the following changes: - **[0cac4d54c](https://github.com/facebook/react/commit/0cac4d54c )**: Double invoked effects on ... — committed to facebook/react-native by sammy-SC 2 years ago
- React Native sync for revisions c28f313...0cac4d5 Summary: This sync includes the following changes: - **[0cac4d54c](https://github.com/facebook/react/commit/0cac4d54c )**: Double invoked effects on ... — committed to OlimpiaZurek/react-native by sammy-SC 2 years ago
@IcebergRage, I got past this, forgot I’d commented anywhere though and it’s a bit fuzzy now.
I believe in my case it was failing when I only had the header for
Content-Type: "multipart/form-data"
as that was enough to make it work on iOS. But, on Android, I also had to specify that I wanted JSON back with the headerAccept: "application/json"
. Simply specified both and 💥.Add this to your manifest
step1> add android:usesCleartextTraffic=“true” line in AndroidManifest.xml like:
<application … android:usesCleartextTraffic=“true”> // add this line … </application>
step2> Delete all debug folder from your android folder…
issue is not fixed then y its closed
Dear fellow developers, please check out my comment on the similar issue #24394 . I hope it will help some of you.
@keyz23 you closed the ticket, but did you find a fix for it?
hey @keyz23 @823844596, I recently encountered something similar using fetch and formDatas (only on Android though). The workaround that worked for me was to use XMLHttpRequest instead of fetch. Hopefully this will help you too!
I don’t know if you are using expo but for me this problem started when I updated my expo SDK from 31 to 33 (so RN 0.57.1 to 0.59.8)
android/gradle.properties
Add this
FLIPPER_VERSION=0.50.0
I think the core issue is the terrible error message. I mean it’s a simply an HTTP request, it’s plain text, so surely it’s possible to get a proper error message from the underlying lib? eg “Missing header”, “Invalid content type”, etc.
When a user of my app sees a “Network request failed” I can only tell them there’s pretty much no way to know what the error is. They have to randomly try every config variations on their server until it works. That’s not how it should be in 2021 - HTTP requests are well understood, and it should be possible to surface a proper error message when something happens.
Solve HTTP and HTTPS Network request failed issue in react native fetch
https://infinitbility.com/network-request-failed-in-react-native-fetch
Thanks for submitting your issue. Can you take another look at your description and make sure the issue template has been filled in its entirety?
👉 Click here if you want to take another look at the Bug Report issue template.
Please avoid doing this.
You are most likely running into this issue because you are trying to develop locally with an emulator and don’t have the correct URL (
10.0.2.2
is the default for AVD).If you need a public URL use https://ngrok.com/ or set up a small VPS with https://certbot.eff.org/
Had a similar problem after upgrading react native, the only way I was able to solve it is using RNFetchBlob, as shown here: https://stackoverflow.com/a/50061209/5724186
I already have this, but still not working 😦
My problem was I did not have internet connection on the emulator, pretty silly, hope it can help someone
No, after 3 days I just trashed the project and switched to flutter, and besides most of the suggested fixes that I found on the net is just a workaround and not even working…
This solution doesnt solve my problem
@jamesjara: Awesome! I just hat to add the “Content-Type” as “multipart/form-data” and “Accept” as “application/json”.–> now it works fine
We’re having the same issue here but on iOS. Using rn 0.53. It was working fine a while ago.
The weird thing is if I have RN Debugger open, our code works. But with remote debugging turned off, everything with fetch returns a Network Request Failed error.
I know that when RN Debugger is open, RN uses V8 to run the code, and when remote debugging is off, it uses the device/simulator’s native JavaScriptCore… I wonder if the most recent version of iOS has an updated version of JavaScriptCore that implements fetch differently from V8?
I’m not educated enough in the internals of javascript engines to get much further than this, though.
Any help would be appreciated.
Hey guys, I had the same problem. I was trying to upload audio .aac file via formData. For me, i had to prepend the
uri
part of the formData withfile://
.Hope it helps someone.
Awesome this worked for me
I have the same problem here, the most curious thing is that this error just happen when it’s a POST request, on my GET requests it’s is working well. Somebody have any ideia?
On postMan my request Workswell too!
My code:
The terminal result :
LOG [TypeError: Network request failed]
The Chrome Debbug (ctrol+m -> Debug) :
TypeError: Network request failed at XMLHttpRequest.xhr.onerror (index.bundle?platfor…&minify=false:26748) at XMLHttpRequest.dispatchEvent (index.bundle?platfor…&minify=false:32302) at XMLHttpRequest.setReadyState (index.bundle?platfor…&minify=false:31386) at XMLHttpRequest.__didCompleteResponse (index.bundle?platfor…&minify=false:31213) at index.bundle?platfor…&minify=false:31323 at RCTDeviceEventEmitter.emit (index.bundle?platfor…e&minify=false:3316) at MessageQueue.__callFunction (index.bundle?platfor…e&minify=false:2648) at index.bundle?platfor…e&minify=false:2361 at MessageQueue.__guard (index.bundle?platfor…e&minify=false:2602) at MessageQueue.callFunctionReturnFlushedQueue (index.bundle?platfor…e&minify=false:2360)
Well to summarize it all, this definitely is not a problem with React Native. I have tested it well with all the scenarios, here are the things you might consider when you get this error:
If you carefully examine above three, you would automatically find out what’s missing, if you do the above in order, I am very sure you should be able to sort it out. Tested it with React 0.64.3
I had fixid this problem in ubuntu and android real device. Folow these steps:
For anyone searching and landing here, I got this error if I feed an array as a value to the FormData object used in the fetch request body. E.g., pseudocode, how to provoke the “TypeError: Network request failed” error on Android:
Headers do not matter, just that it’s a POST request.
I have the same issue. Did any one was able to solve it?
Was anyone able to solve it?? I am facing similar issue with fetch. I have to use common code for android and iOS. fetch works great in iOS but in android throws error.
Trying to fetch data from remote server via api. Using fetch(https:url:port) to fetch the data. But every time android emulator as well as physical device gives network request failed. While I can access same url within browser of emulator.
I have already went through various links, and many people have posted same problem but none of them had ample solution that works. While some people were not able to access localhost via api-call but it was resolved using IP address of system. But in my scenario I am trying to access remote host. Also domain name cannot be used in my scenario, so need a solution using (ip) in fetch method=get.
testlogin = https://10.209.7.115:8080/api/v1/ Basicauth = ‘Basic cm9vdDpyb290’
fetch(testingLogin, { method: “GET”, cache: “no-cache”, mode: “cors”, withCredentials: true, credentials: “include”, headers: { ‘Authorization’:Basicauth, Accept: “application/json”, “Content-Type”: “application/json” } }).then(response => { if(response.status === 200) { this.props.navigation.navigate(‘Home’); } else { alert(“Authorization failed”); } }) .catch(error => { alert("Request Failed :Check the ip address Entered:Problem with server "); throw(error);
Error:
TypeError: Network request failed onerror@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:24051:31 dispatchEvent@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:28695:31 setReadyState@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:28448:33 __didCompleteResponse@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:28275:29 emit@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:3280:42 __callFunction@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:2577:49 http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:2334:31 __guard@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:2531:15 callFunctionReturnFlushedQueue@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:2333:21
I had the similar issue. I was setting incorrect
type
inFormData
object: it wasimage
instead ofimage/jpeg
orimage/png
orimage/whatever
. My code was:And the working one:
It’s July-2021, and the problem has never been solved?
Based on this code https://github.com/facebook/react-native/blob/476a336e3613f90b76e3a91d5bffaa098bf4e6ff/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java#L383 any request without headers content-type and payload body as string will start failing into “Network request failed.” this is because the high-level wrappers are handing the Request Error call as “Network request failed.” but is not even reaching the internet.
That solution worked for me .
I believe in my case it was failing when I only had the header for Content-Type: “multipart/form-data” as that was enough to make it work on iOS. But, on Android, I also had to specify that I wanted JSON back with the header Accept: “application/JSON”. Simply specified both and 💥.
Same issues in here. Fetch does not work well in Andorid. Sometimes it returns error that is Network request failed. It works well only IOS. Is there any solutions to solve this?
I fixed it by commenting a line in the /android/app/src/debug/java/com/{your-app-name}/ReactNativeFlipper.java file. this is only fix that worked for me!
new NetworkingModule.CustomClientBuilder() { @override public void apply(OkHttpClient.Builder builder) { // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); } });
I have same problem on RN 0.62 😦 Working fine in release but in debug very annoying!
Here’s how I resolved this.
The server expects
multipart/form-data
for file uploads, but it seems that the request is being sent with application/x-www-form-urlencoded instead. This discrepancy causes the server to reject the request on Android, it works fine on iOS.The native error looks like this
Explicitly setting the content type via the header fixed the issue.
Adding
multipart/form-data
to the request header fixed the issue for me.This worked for me on EXPO SDK 49: I’ve installed
expo-build-properties
usingnpx expo install expo-build-properties
and then added it as a plugin inapp.json
:remove from-data solved in my case
var myHeaders = new Headers(); myHeaders.append(“auth-token”, ids.token); var formdata = new FormData(); var requestOptions = { method: ‘PUT’, headers: myHeaders, // body: formdata, redirect: ‘follow’ };
return fetch(baseUrl+“api/v1/trip/”+ids.uId+‘/’+ids.tripId+‘/views’, requestOptions) .then(response => {
}) .then(result => { return result }) .catch(error => console.log(‘error’, error));
It’s still not solved with me. I tried using my machine’s IP address instead of localhost but that didn’t work for me. Anyone else facing the same problem?
“http://ip:port” format may be useful for android device.
its working for me url should be 10.0.2.2:3000/singup localhost will not work if you are sending from real android device use your pc ip address
same here, I can’t get this to work with just a simple get request from a secured api, here is the snippet:
fetch(‘https://domainofapi/api/emp/position/all’, { method: ‘GET’, cache: ‘no-cache’, mode: ‘cors’, headers: { ‘Accept’: ‘application/json’, }, }) .then(response => response.json()) .then(json => setPositions(json));
tried almost every solution I can find, usesCleartextTraffic, network security config, etc.
@dotfelixb thanks for your answer. I found out, problem was with fetch request, so, to solve this problem, Im using RNFetchBlob(https://github.com/joltup/rn-fetch-blob) library, for sending files to server. But lately i’ll check your solution.
Same issue. Still no fix?
For me, it was solved in a quite simple way:
->
Thanks, it’s work for me
If you are developing on mac and using wifi. Must remember add DNS (e.g. 8.8.8.8). It works for me.
I changed api url ‘localhost’ to real host, it works!!! And 127.0.0.1 dons’t work also
Hope this issue will reopen.
If that can help anyone, React Native 0.62+ seems to require a “Content-Type” header for certain fetch calls or else you get “Network request failed”. More info in this issue: https://github.com/facebook/react-native/issues/30176
Is this something new that appeared in a patch release? Because when I started my RN project the same code I have now could connect to the https Server I’m using.
@alanhalpern06 All should be well with these changes
- data.append('dateBegin', dateBegin);
+ data.append('dateBegin', dateBegin.toISOString());
- data.append('dateEnd', dateEnd);
+ data.append('dateEnd', dateEnd.toISOString());
- 'Content-Type': 'application/json',
+ 'Content-Type': 'multipart/form-data',
Hi all, we have a discussion here tracking this: https://github.com/facebook/react-native/issues/28551
There are a series of workarounds, mentioned in the thread. Check it out!
This is not a react native specific issue, is more of Android 9.
same problem looks like no body is fixing this problem
Its
void
method 😃 it is not returning anything even when not commented 😉In my case it was only not working for localhost URLs. I changed
localhost
in the URL to my local IP and it worked. (RN 0.62.2)I also tried using XMLHttpRequest, but its returning me error 406
@dotfelixb thanks for your feedback. Deleting the folder didn’t fix the issue 👎 unfortunately. I switched to rn-fetch-blob to make my upload work.
This is a problem with the cert. Your server should use intermediate certificates so Android should not reject the requests.