react-native
react-native copied to clipboard
[Only Android] fetch Error : [Network request failed]
Description
---My Code---
const reverseGeocoding = async (location: Location) => {
const params = new URLSearchParams({
"orders": `admcode`,
"output": "json",
"coords": `${location.longitude},${location.latitude}`
}).toString()
const resultBare = await fetch(`${Config.REVERSE_GEOCODING_URL}?${params}`, {
method: "GET",
headers: {
"X-NCP-APIGW-API-KEY-ID": `${Config.NCP_AI_CLIENT_ID}`,
"X-NCP-APIGW-API-KEY": `${Config.NCP_AI_CLIENT_SECRET}`,
}
})
const jsonResult = await resultBare.json()
console.log(JSON.stringify(jsonResult))
return jsonResult;
}
---Not working solution---
- android:usesCleartextTraffic="true"
- commenting out line number 43 in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java
38 NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39 NetworkingModule.setCustomClientBuilder(
40 new NetworkingModule.CustomClientBuilder() {
41 @Override
42 public void apply(OkHttpClient.Builder builder) {
43 // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44 }
45 });
46 client.addPlugin(networkFlipperPlugin);
27 # Version of flipper SDK to use with React Native
28 FLIPPER_VERSION=0.39.0 // edit this manually
its too old solution my code already 0.99.0
---Error---
Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:25357:33
http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:29572:26
_callTimer@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:29492:17
callTimers@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:29693:19
__callFunction@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:3056:36
http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:2780:31
__guard@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:3007:15
callFunctionReturnFlushedQueue@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:2779:21
callFunctionReturnFlushedQueue@[native code]
fetch not working only android emulators , physical device too
Version
0.66.4
Output of npx react-native info
System: OS: macOS 11.1 CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz Memory: 3.60 GB / 32.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 17.3.1 - /usr/local/bin/node Yarn: Not Found npm: 8.3.1 - /usr/local/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman Managers: CocoaPods: 1.11.2 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4 Android SDK: Not Found IDEs: Android Studio: 4.2 AI-202.7660.26.42.7351085 Xcode: 12.5.1/12E507 - /usr/bin/xcodebuild Languages: Java: 11.0.9.1 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 17.0.2 => 17.0.2 react-native: 0.66.4 => 0.66.4 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found
Steps to reproduce
just using fetch, axios etc... any networking tools
Snack, code example, screenshot, or link to a repository
No response
Have the same problem: [TypeError: Network request failed]
System: OS: Windows 10 10.0.21996 CPU: (16) x64 AMD Ryzen 7 4800H with Radeon Graphics Memory: 3.39 GB / 15.42 GB Binaries: Node: 17.0.1 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.17 - ~\AppData\Roaming\npm\yarn.CMD npm: 8.1.0 - C:\Program Files\nodejs\npm.CMD Watchman: Not Found SDKs: Android SDK: Not Found Windows SDK: Not Found IDEs: Android Studio: Version 2021.1.0.0 AI-211.7628.21.2111.8139111 Visual Studio: Not Found Languages: Java: Not Found npmPackages: @react-native-community/cli: Not Found react: 17.0.1 => 17.0.1 react-native: 0.64.3 => 0.64.3 react-native-windows: Not Found npmGlobalPackages: react-native: Not Found
Same problem :
System:
OS: Windows 10 10.0.19043
CPU: (12) x64 AMD Ryzen 5 2600 Six-Core Processor
Memory: 4.31 GB / 15.93 GB
Binaries:
Node: 14.18.2 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 7.24.2 -C:\Program Files\nodejs\npm.CMD
Watchman: Not Found
SDKs:
Android SDK: Not Found
Windows SDK:
AllowDevelopmentWithoutDevLicense: Enabled
AllowAllTrustedApps: Enabled
Versions: 10.0.10240.0, 10.0.19041.0
IDEs:
Android Studio: Not Found
Visual Studio: 16.11.32002.261 (Visual Studio Community�2019)
Languages:
Java: javac 12 - C:\Program Files\Common Files\Oracle\Java\javapath\javac.EXE
npmPackages:
@react-native-community/cli: ^5.0.1 => 5.0.1
react: 17.0.2 => 17.0.2
react-native: 0.67.3 => 0.67.3
react-native-windows: Not Found
npmGlobalPackages:
react-native: Not Found
In my case, I was trying to upload a file with multipart/form-data but apparently fetch can't handle blob files. It works fine if I don't append the file but fails with an uninformative error if I do. I now use rn-fetch-blob which can handle uploading binary data.
Any Update? Facing the Same Issue
Any update? Same issue on any request. Neither adb -s <device> reverse tcp:8080 tcp:8080
nor network_security_config.xml
nor usesCleartextTraffic
helped
react-native: 0.68.1
Any Update? Facing the Same Issue
System: OS: macOS 12.4 CPU: (8) x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz Memory: 509.63 MB / 16.00 GB Shell: 5.8.1 - /bin/zsh Binaries: Node: 16.14.2 - ~/.nvm/versions/node/v16.14.2/bin/node Yarn: 1.22.15 - ~/.nvm/versions/node/v16.14.2/bin/yarn npm: 8.5.0 - ~/.nvm/versions/node/v16.14.2/bin/npm Watchman: 2022.03.21.00 - /usr/local/bin/watchman Managers: CocoaPods: 1.11.3 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5 Android SDK: API Levels: 30, 31, 32 Build Tools: 30.0.2, 30.0.3, 31.0.0, 32.0.0, 32.1.0 System Images: android-30 | Google APIs Intel x86 Atom Android NDK: Not Found IDEs: Android Studio: 2021.1 AI-211.7628.21.2111.8193401 Xcode: 13.4/13F17a - /usr/bin/xcodebuild Languages: Java: 11.0.11 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 17.0.2 => 17.0.2 react-native: 0.68.1 => 0.68.1 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found
fixed TypeError: Network request failed
when upload file to http not https with Android debug builds
In react-native 0.63.2 (I'm testing) or some higher version, if just use fetch
to upload file to a http (not https) server, will meet TypeError: Network request failed
.
Here I use axios@0.27.2 as client running on an Android phone successfully upload a file to react-native-file-server as server running on another Android phone.
client need edit JAVA and JS code, server no need edit JAVA code.
With debug builds, must commenting out line number 43 in this file android/app/src/debug/java/com/YOUR_PACKAGE_NAME/ReactNativeFlipper.java
38 NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39 NetworkingModule.setCustomClientBuilder(
40 new NetworkingModule.CustomClientBuilder() {
41 @Override
42 public void apply(OkHttpClient.Builder builder) {
43 // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44 }
45 });
46 client.addPlugin(networkFlipperPlugin);
Maybe also need add android:usesCleartextTraffic="true"
under <application
of android/app/src/main/AndroidManifest.xml
, on my test, it's not necessary on both debug and release builds.
onFileSelected = async (file) => {
// API ref to the server side BE code `addWebServerFilter("/api/uploadtodir", new WebServerFilter()`
// https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L356
// could not be 'localhost' but IP address
const serverUploadApi = 'http://192.168.1.123:8080/api/uploadtodir';
// the folder on server where file will be uploaded to, could be e.g. '/storage/emulated/0/Download'
const serverFolder = '/storage/emulated/0/FileServerUpload';
const fileToUpload = {
// if want to upload and rename, it can be `name: 'foo.bar'`, but can not be 'foo'
// only if your server upload code support file name without type, on our server
// https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L372
// will cause java.lang.StringIndexOutOfBoundsException in substring()
name: file.name,
// type is necessary in Android, it can be 'image/jpeg' or 'foo/bar', but can not be
// 'foo', 'foo/', '/foo' or undefined, otherwise will cause `[AxiosError: Network Error]`
type: 'a/b',
uri: Platform.OS === 'android' ? file.uri : file.uri.replace('file://', ''),
};
const form = new FormData();
form.append('path', serverFolder);
form.append('uploadfile', fileToUpload);
// ref to the server side FE code `this.axios.post("/api/uploadtodir", parms, config)`
// https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/fileserverwebdoc/src/views/Manage.vue#L411
let res = await axios.post(serverUploadApi, form, {
headers: {
'Content-Type': 'multipart/form-data',
},
onUploadProgress: function (progressEvent) {
console.warn(progressEvent);
},
});
// ref to the server side BE code `return newFixedLengthResponse("Suss");`
// https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L380
if (res.data === 'Suss') {
console.warn('Upload Successful');
} else if (res.data === 'fail') {
console.warn('Upload Failed');
}
};
any update on this?
Same issue
Any Update? Facing the same problem :s
Any update? I'm facing the same issue with both Axios and React Native's Fetch =/
Any update? we are facing the same problem and the proposed fix has not worked. We are using:
- react-native: 0.70.1
- react: 18.1.0
- FLIPPER_VERSION=0.125.0 (this version is the one set in
gradle.properties
)
Thank you,
I have the same problem here. Problem occurs on old android, tested on android 6 and 7
Tested Versions
- react-native: 0.70.2 and 0.70.4
- axios: 0.21.4 - 0.27.2
- targets sdk 31 and 33
I have the same issue, started happening after upgrading from RN 0.66.4 to 0.70.5
- react-native: 0.70.5
- react: 18.1.0
- flipper: 0.125.0
I have also tried all the proposed solutions above without any success.
I have a similar problem, If you directly use the instance of new FormData() to assemble the Form Data parameter, you will be prompted [AxiosError: Network Error]
- react 18.1.0
- react native 0.70.2
- axios 0.27.2
- FLIPPER_VERSION 0.125
for example:
export function login(data) {
const formData = new FormData()
formData.append('username', data.username)
formData.append('password', data.password)
return axios.post('/api/user/login', formData)
}
It will prompt [AxiosError: Network Error]
But I used the following two methods to make the request successful:
-
- string
export function login(formData: LoginDataType) {
const data = `username=${formData.username}&password=${formData.password}`
return axios.post('/api/user/login', data)
}
-
- use 'qs'
import axios from 'axios'
import qs from 'qs'
export function login(formData: LoginDataType) {
return axios.post('/api/user/login', qs.stringify(formData))
}
I don't know if the situation is the same as yours. I hope I can help you.
Sorry, my English is poor
Same as ugglr, it was working fine on RN 0.66.4 but upgrading to 0.70 caused it to stop working; same fetch request (uploading a file using FormData) works fine on iOS but throws a FETCH_ERROR on android; stringifying doesn't seem to help.
Any update ? i'm getting this error trying send a file in request
For me, I was able to fix this by adding a mime-type of the file to the upload (wasn't required previously or on iOS):
const chunk = {
uri: `file://${file.path}`,
type: "application/octet-stream", // I wasn't including this; works if I use the proper type (e.g. image/jpeg) as well
name: file.name,
size: file.size
}
const formData = new FormData();
formData.append("Chunk", chunk);
formData.append("OtherData", data);
await axios.post("upload", formData, {
headers: {
"Content-Type": `multipart/form-data`,
},
});
Hope that helps someone
@fwestling-lor and if i send a pdf, is the same type ??
because this go block on backend, the backend system only accept pdf type
Ok this work for me thanks @fwestling-lor
TL;DR Do not add undefined for file information in form data.
This is strange. Over the last 2+ months, I was able to send a POST request w/ multipart/form-data where the images were undefined (when the user didn't add a file).
The request goes through and reaches the backend and my server responds to the request successfully. However, the fetch reports the error [TypeError: Network request failed] and not the response from my server.
This became apparent on the frontend when my app didnt navigate back after the request was sent since an error was thrown. What is strange is, I have haven't touched this bit of code in a while and all of a sudden it stopped behaving as expected and that's when I noticed the [TypeError: Network request failed] error.
Issue adding undefined values for file:
data.append('main', {
uri: mainFile.uri,
name: mainFile.fileName,
type: mainFile.type,
});
// form data parts - data.getParts()
{"fieldName": "main", "headers": {"content-disposition": "form-data; name=\"main\""}, "name": undefined, "type": undefined, "uri": undefined}
For me, I was able to fix this by adding a mime-type of the file to the upload (wasn't required previously or on iOS):
const chunk = { uri: `file://${file.path}`, type: "application/octet-stream", // I wasn't including this; works if I use the proper type (e.g. image/jpeg) as well name: file.name, size: file.size } const formData = new FormData(); formData.append("Chunk", chunk); formData.append("OtherData", data); await axios.post("upload", formData, { headers: { "Content-Type": `multipart/form-data`, }, });
Hope that helps someone Thank You. This Solved the Issue.
I have same issue. It works on iOS, but not on Android. By the way, sending first picture in post request fails, but second is ok, third in not etc. Nothing suggested in the sources helps
I'm having the same issue today. It happens SOMETIMES. Other times, the image (FormData) posts and gets stored in the uploads folder (via a PHP script) just fine! Filesize doesn't seem to matter. Tried adding a 3 second delay. Did the "line 43 comment out" as well as ClearText in the Android.XML file. Pretty much tried EVERYTHING everyone has been suggesting. STILL having the problem.
For me, I was able to fix this by adding a mime-type of the file to the upload (wasn't required previously or on iOS):
const chunk = { uri: `file://${file.path}`, type: "application/octet-stream", // I wasn't including this; works if I use the proper type (e.g. image/jpeg) as well name: file.name, size: file.size } const formData = new FormData(); formData.append("Chunk", chunk); formData.append("OtherData", data); await axios.post("upload", formData, { headers: { "Content-Type": `multipart/form-data`, }, });
Hope that helps someone
Awesome!! You saved my day!! I work with RTK Query and only had to change the type in the FormData files chunk. Indeed only on Android...on iOS is was fine before and stil is with type: "application/octet-stream"
I had this problem with Expo 49 and RN 0.7.2.4
After countless hours battling with the same issue, I figured out the problem. I was sending a dictionary as a value for one of the form keys. JSON.stringify the key worked. Also I had an audio file in the payload.
Spent few hours and research a bit. There's a problem on android with request url.
Condition 1: Not Working on Android
API: RTK Query
Server base url: http://localhost:8080
Works well on iOS but not works on Android
Condition 1: Works in both platforms
API: RTK Query
Server base url: http://192.168.1.1:8080
(ipv4)
Works well on both platforms.
POSIBLE SOLUTION
I faced the same problem (iOS working & Android failure) and in the end it turned out to be a problem because the domain to which the request was made contained an underscore (_) character. Removing the underscore by a dash solved the problem.
Previos domain https://my_domain.com
Working domain https://my-domain.com
If you are using a domain other than localhost and use special characters it is possible that it may fail because of this. I will update my comment if I find any additional information.
I hope it helps 🙏🏻
Spent few hours and research a bit. There's a problem on android with request url.
Condition 1: Not Working on Android
API: RTK Query Server base url:
http://localhost:8080
Works well on iOS but not works on Android
Condition 1: Works in both platforms
API: RTK Query Server base url:
http://192.168.1.1:8080
(ipv4)Works well on both platforms.
after adding the highlighted line in android/app/src/main/AndroidManifest.xml
then using serverbaseUrl(machine ipv4 address) as commented here. working fine for me.