Axios network error even though the post request returns 200 - react-native

After enabling CORS and everything on my server, the error persists.
In other forms inside my app, uploading pictures works... but in this exact form, on iPhone it works absolutely fine, but on android after submitting, all I get is a "network error" although the post returns 200. I think this is an axios problem. Only on android I get this issue.
my code is the following:
const data = new FormData()
data.append('subject_id', this.props.navigation.getParam('id'))
data.append('name', this.state.title)
data.append('progress', this.state.progress * 100)
data.append('description', this.state.description)
data.append('date', this.state.date)
data.append('image', {
uri: this.state.image,
type: 'image/jpeg',
name: 'image'
});
axios.post('https://example.com/api/auth/createTask', data, {
headers: {
'Authorization': access,
"Content-Type": "multipart/form-data"
},
}).then(res => {
this.props.navigation.navigate('ViewHW', { id: res.data.id })
}).catch(res => {
console.log(res)
})
I would really appreciate the help on this one.

I doubt that it's an axios issue.
If you're using an image picker or camera make sure you check the documentation as the path to the file selected differs between android and iOS.
Make sure you change the path of the item based on platform.OS === 'android'.
It should be clearly described in the docs of whatever you're using.

This ended up being a problem with react-native. The bug is now patched (the new version 0.63.3)

Related

HTTP requests does not work on my real android device (React Native Expo Tunnel)

I'm facing this issue while posting data to my server via axios.post(). It always catches the error "Network Error" when I run my app on my real android device. But when I use an android emulator device, it works correctly and returns the response. I tried to use "ngrok http 5000" and used the uri that ngrok gave me but that didn't work either. I'm hopeless at this point because my app is using QR code scanner and indie notifications. I'm unable to test it while using emulator. Please help me!
I'm leaving my axios.post() method below
const login = async (email, password, navigation) => {
userState.loading = true;
axios
.post(`http://${localIP}:5000/api/user/login`, {
email,
password,
})
.then((response) => {
userState.loading = false;
userState.user = response.data;
console.log("Data: ", response.data);
navigation.reset({
index: 0,
routes: [{ name: "Home" }],
});
})
.catch((err) => {
userState.loading = false;
console.log("ERR :", err.message);
});
};
I tried to use "ngrok http 5000" and used the uri that ngrok given me but that didn't work either.
Might be a little light on information in order to give a definite answer, it's worth looking at installing a debugger and inspecting the network requests to see where they're going wrong. But here's a couple things to try:
In your AndroidManifest.xml file add the line: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Use http://my.local.ip:port instead of http://localhost:5000 (looks like you're doing this anyway, if not you get this via ipconfig in Command Prompt)
Try adding "Content-Type": "application/json", Accept: "application/json" headers to your Axios request

form post with file attach throws network error / React Native + react native Image picker

I am using react-native-image-picker to fetch image details and try to upload in https backend server. the request is not successful and it throws network error. It did not esablish the connection with the backend server. The problem is with formdata that I am sending. Can you please suggest header and other information, if I missed out.
export const postImage = async state => {
let formData = new FormData();
formData.append('image', {
uri : state.photo.uri,
type: state.photo.type,
name : state.photo.fileName
});
const config = {
headers: {
'Content-Type': 'multipart/form-data',
Accept: "application/x-www-form-urlencoded",
'Accept': 'application/json'
},
};
try {
return $http.post('/image/save', formData, config)
.then(response => response)
.catch(error => error)
} catch(error) {
console.log(error)
}
}
Environment:
- Axios Version ^0.19.2
- Additional Library Versions [React 16.11.0, React Native 0.62.1]
There's an issue with flipper, upgrading it to 0.39.0 and above works
This issue is being tracked here: https://github.com/facebook/react-native/issues/28551
Fix: https://github.com/facebook/flipper/issues/993#issuecomment-619823916
This should be fixed in version 0.39.0. To upgrade, edit android > gradle.properties
# Version of flipper SDK to use with React Native
FLIPPER_VERSION=0.39.0 // edit this manually
This issue took me more than 5 hours to resolve. I was about to give up when I was finally able to resolve the issue.
The issue that I was facing which is close to what you are mentioning is that I was getting NetworkError when using expo-image-picker and trying to upload the file using axios. It was working perfectly in iOS but not working in android.
This is how I solved the issue.
There are two independent issues at action here. Let's say we get imageUri from image-picker, then we would use these following lines of code to upload from the frontend.
const formData = new FormData();
formData.append('image', {
uri : imageUri,
type: "image",
name: imageUri.split("/").pop()
});
The first issue is with the imageUri itself. If let's say photo path is /user/.../path/to/file.jpg. Then file picker in android would give imageUri value as file:/user/.../path/to/file.jpg whereas file picker in iOS would give imageUri value as file:///user/.../path/to/file.jpg.
The solution for the first issue is to use file:// instead of file: in the formData in android.
The second issue is that we are not using proper mime-type. It is working fine on iOS but not on Android. What makes this worse is that the file-picker package gives the type of the file as "image" and it does not give proper mime-type.
The solution is to use proper mime-type in the formData in the field type. Ex: mime-type for .jpg file would be image/jpeg and for .png file would be image/png. We do not have to do this manually. Instead, you can use a very famous npm package called mime.
The final working solution is:
import mime from "mime";
const newImageUri = "file:///" + imageUri.split("file:/").join("");
const formData = new FormData();
formData.append('image', {
uri : newImageUri,
type: mime.getType(newImageUri),
name: newImageUri.split("/").pop()
});
This is an issue with flipper.Upgrade the flipper version in gradle.properties to 0.43.0+ and it will be fixed
Make sure the mime type matches the file you are uploading.
For me, it was the issue.
change this line: form_data.append('image', data);
To form_data.append('image', JSON.stringify(data));
where data is from the image picker.
from https://github.com/react-native-image-picker/react-native-image-picker/issues/798
You need to add this uesCleartextTraffic="true" to the AndroidManifest.xml file found inside the dir android/app/src/main/AndroidManifest.xml
<application ... android:usesCleartextTraffic="true"> Then, Because of issue with Flipper Network.
I commented initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
in this file /android/app/src/main/java/com/{your_project}/MainApplication.java
Also, commenting out line number 43 in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java
line43: builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
None of the issues in the other answers were causing my problem, but after digging more into Axios error response, I found out that Nginx was responding with error 413 Request Entity Too Large.
Adding client_max_body_size 50M to the http section of nginx.conf file solved the issue.

React native 'Network error' with post Custom header and form data

I am trying to upload some data using axios post request and custom headers. Here is my code.
axios
.post('https://website.domain/api/ads/create', new FormData(), {
headers: {
Authorization: 'Bearer 123',
},
})
.then(res => {
this.setState({ message: JSON.stringify(res) });
})
.catch(res => {
this.setState({ message: JSON.stringify(res.response) });
});
this works fine with Expo (here is the source)
But when move to react native it does not work. It gives me the error:
{message:"Network error".....}
PS: other methods like post without authorization, get all are working except this one.
I found the solution! The trick was with uploading the file: with expo you need to remove //file prefix of file path while in react-native it should be preserved!

react-native fetch network request failed on IOS although "allow arbitrary loads" set to YES

Within my react-native app, I get network request failed error on IOS simulator after fetching GET method. I tried on Android and it worked perfectly. I know that for IOS I need to set Allow Arbitrary Loads to "yes" in info.plist in Xcode,but I did it long time ago. Beside, I have lots of other pages(components) that I fetch requests and I do not live any problem on these components. I believe maybe it is something related to URL or response.
Here is my info.plist file
Here is the json that I supposed to get as response of fetch GET method.(BTW, I get the supposed response in ANDROID)
const { dispatch } = this.props;
console.log("Whitespot MAPS Props: ",this.props);
url = '-----------------/coordinates?product=1';
requestOptions = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + this.props.token
}
};
dispatch(authActions.checkTokenAndFetch(url, requestOptions))
.then((data) => {
console.log("COORDINATES: ",data);
},
(error) => {
console.log("MAP COORDINATES ERROR: ",error);
})
And here is the error I get while running on IOS simulator
I solved the issue. Beside, arbitrary loads, I also need to give permission directly to my server url in info.plist Exception Domains section. So, it works out in this way. Have a good day.
Just like in pic.

Uploading videos using formdata in react native

Has anyone successfully uploaded a video via React Native Formdata()? The code below attempts to upload a .mov file from the camera roll URI but in fact only the first frame of the video (a JPEG) gets uploaded. What's the issue here?
var movVideo = {
uri: uriFromCameraRoll,
type: 'video/quicktime',
name: 'something.mov',
};
var body = new FormData();
body.append('video', movVideo);
body.append('title', 'A beautiful video!');
fetch('https://mysite/upload_asset', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: body,
}).then((response) => response.json())
.then((responseJson) => {
//only the first frame of the video got uploaded
console.log(responseJson);
});
Had the same issue. Looks like React Native does not return the correct stream for videos with asset library URIs. Pictures seem to work fine. I would need to dig deeper before submitting an issue though.
I suggest you take a look at react-native-fetch-blob, which provides an improved fetch polyfill with Blob support. This implementation handles videos from the camera roll just fine. Also, the changes needed to use this module are minimal (include the polyfill, wrap URI with RNFetchBlob.wrap).