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');
}
};
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');
}
};
Пытаюсь отправить запрос HTTP. Ошибка: Network request failed. в info.plist прописал NSAllowsArbitraryLoads = true, перезапускал приложение react-native run-ios
но всё равно эта ошибка.
-
Вопрос заданболее трёх лет назад
-
2887 просмотров
обнови react-native или попробуй более старую версию андроида, ios, это может быть из за того что функция fetch в старой версии react-native работает некорректно в новых версиях прошивки
Пригласить эксперта
-
Показать ещё
Загружается…
05 июн. 2023, в 19:29
1000 руб./за проект
25 мая 2023, в 11:04
3000 руб./в час
22 мая 2023, в 18:02
120000 руб./за проект
Минуточку внимания
Hello Friends 👋,
Welcome To Infinitbility! ❤️
Getting error TypeError Network request failed
in android, ios, or with SSL server then read all below cases.
In this article, we solve 3 cases of network request failed issue in react-native but your condition does not match with the below mention cases then comment below on the article.
Case 1: http url not working in android
if you are trying to call HTTP ( unsecured ) url then you have to add usesCleartextTraffic
to your AndroidManifest.xml
.
AndroidManifest.xml
<application
...
android:usesCleartextTraffic="true" <!-- add this line -->
>
...
</application>
***Trying to call localhost api with diffrent port? ***
Replace localhost with your ipaddress v4
To know your ipv4
- For windows users
- For Mac or linux users
HTTP URL not working in ios
If you are trying to call an unsecure url from reac native ios.
you have to do below changes on your info.plist to allow unsecure url
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
HTTPS URL not working in android react native fetch
You are trying to call HTTP URL from react-native fetch but getting Network request failed to issue or in ios working fine then below the solution for you only.
This has to do with Android not trusting my SSL certificate. Apparently Android has some additional trust requirements on top of what web browsers require.
After figuring that out, the root cause ended up being my SSL Certificate uploaded to AWS didn’t have the correct intermediate cert which was fine in chrome, but not in android.
check your SSL certificate set up perfectly or not on https://www.digicert.com/help/.
when you get an error on DigiCert assign a task to your server administrator 😁.
Thanks for reading…
More From React Native Tutorial
Basics
1. Introduction To React Native
2. React Native Environment Setup using expo
3. React Native Environment Setup for windows
4. React Native Environment setup on Mac OS
5. React Native Environment setup on linux
6. React Native Project Structure
7. React Native State
8. React Native Props
9. React Native Styling
10. React Native Flexbox
11. React Native Text
12. React Native Textinput
13. React Native Commands
14. React Native ScrollView
Advances
1. React Native Dark Mode
2. React Native Fonts
3. React Native SQLite
4. React Native DatepickerAndroid
5. React native ScrollView scroll to position
6. How to align icon with text in react native
7. React Native Image
8. React Native Firebase Crashlytics
9. React Native Async Storage
10. React Native Share
Error & Issue Solution
1. Task :app:transformDexArchiveWithDexMergerForDebug FAILED In React Native
2. Expiring Daemon because JVM heap space is exhausted In React Native
3. Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED In React Native
4. Unable to determine the current character, it is not a string, number, array, or object in react native
5. App crashed immediately after install react native video or track player
6. how to delete SQLite database in android react native
7. React native material dropdown twice click issue
8. How to get the current route in react-navigation?
9. how to disable drawer on the drawer navigation screen?
10. Image not showing in ios 14 react native
11. React Native image picker launchimagelibrary on second time issue
12. how to open any link from react native render Html
13. Network request failed in react native fetch
14. React Native upload video example
If you are currently working on an app with React Native and you are using Laravel as your backend, you have probably encountered this problem.
And this article will help you solve this problem with just ONE SIMPLE TRICK.
SOMETIMES THIS PROBLEM IS CAUSED BY HOW YOU START YOUR LARAVEL APP
We all know how to start a Laravel server with the simple php artisan serve command and that’s the problem.
By starting your Laravel app like that it creates a link for your app which is localhost:8000 (the port may be different for you, it might be 3000, 8080 or anything else but we will use 8000 for this tutorial).
When making an HTTP Request with React Native, there is some kind of conflict because your Android app is run on an emulator which uses localhost too, and instead of sending the request to the localhost on your computer, it sends the request to the phone itself but with a different port and that is why you are getting this error.
THE TRICK THAT HELPED ME
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.
D:xampphtdocsprojectslaravelblog>php artisan serve --host 10.10.10.2 --port="8000"
Laravel development server started: http://10.10.10.2:8000
Enter fullscreen mode
Exit fullscreen mode
Just start the server by giving an IP address and a port
It’s just that simple! Start your app as usual but don’t forget to give an IP address and a port, this will help you solve the Network Request Failed error.
NOTE: Replace 10.10.10.2 with your own IP Address, this is just an example.
//with axios
await axios.post('http://10.10.10.2:8000/api/user/login', data, headers)
.then(res => {
console.log(res.data)
})
//with Fetch
await fetch('http://10.10.10.2:8000/api/user/login', {
method: "POST",
headers: headers //put your headers,
body: body //put the body here
})
Enter fullscreen mode
Exit fullscreen mode
And on your mobile app, make sure to use the correct URL in your request.
Make sure that CORS is enabled in your backend to avoid errors related to CORS. Next time I will make make a detailed post about how to enable it and how to solve issues related to CORS.
CONCLUSION
Start your Laravel app and enter your IP address and a port
Use the URL in your HTTP Request.
That’s it, I hope this post was useful to you and happy coding!