Network Error While making axios call with Form Data - react-native

We have an application where we need to upload documents or images:
react: 17.0.2
react-native: 0.68.2
axios: 1.3.2
While making web service call using axios, we are getting Network Error in both iOS and Android.
Same API is working in web and through Postman.
Code (Same code is working fine with Json data.)
try {
var formData = new FormData();
formData.append('file', fileUpload);
const obj = { hello: "world" };
formData.append('param', JSON.stringify(obj));
const response = await axios({
method: 'post',
url: 'https://xxxxxxxxxxx.com/fr_webservice/file/doUpload',
data: formData,
headers: {
'x-auth-token': authData.token,
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data"
},
});
console.log("[Form Data Response]: ", response);
} catch (error) {
console.log("[Form Data Error]: ", error);
}
"AxiosError: Network Error
at XMLHttpRequest.handleError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:191293:16)
at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:26337:27)
at XMLHttpRequest.setReadyState (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25607:20)
at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25417:16)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25543:47
at EventEmitter.emit (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:1731:37)
at MessageQueue.__callFunction (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2533:31)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2302:17
at MessageQueue.__guard (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2492:13)
at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2301:14)"

Related

multipart/form-data request failing in react-native

I get the following error when I set the 'Content-Type' as 'multipart/form-data' in react-native.
Below is my code -
const formData = new FormData();
formData.append('org_id', org_id);
formData.append('ans', userAns);
formData.append('remark', userRemark);
formData.append('img', userImg);
files.forEach(file => {
formData.append('files', {
name: file.fileName,
type: file.type,
uri: file.uri,
});
});
const resp = await multiPartInstance({
method: 'PUT',
url: `${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
data: formData,
});
return Promise.resolve(true);
I am using axios for calling apis. multiPartInstance is an axios instance -
const multiPartAccessToken = async (config: AxiosRequestConfig) => {
config.headers = {
Accept: 'application/json',
access_token: useTokenStore.getState().accessToken,
'Content-Type': 'multipart/form-data;',
};
config.timeout = 30000;
return config;
};
I've tried the above with fetch also but I keep getting the same error. The strangest part is that this request hits the server, server sends a response too but I get this error react-native side. I've noticed if I don't use FormData I don't get any error. But I need to use FormData as I have to upload image files.
Environment Details -
Windows version 21H2 (OS Build 22000.376)
react-native 0.66.3
react 17.0.2
axios ^0.24.0
react-native-image-picker ^4.3.0 (used for selecting images)
Flipper version 0.99.0
I've tried the solutions posted on below forums but they didn't work for me.
request formData to API, gets “Network Error” in axios while uploading image
https://github.com/facebook/react-native/issues/24039
https://github.com/facebook/react-native/issues/28551
I am as follow and works perfectly:
const oFormData = new FormData();
images.map((val, index) => {
oFormData.append("image", {
uri: val.uri,
type: val.type,
name: val.fileName
});
});
return axios.post(postServiceUrl, oFormData);
Somehow react-native-blob-util doesn't give this error. I modified my code as below -
import ReactNativeBlobUtil from 'react-native-blob-util';
const fileData = files.map(file => {
return {
name: 'files',
data: String(file.base64),
filename: file.fileName,
};
});
try {
const resp = await ReactNativeBlobUtil.fetch(
'PUT',
`${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
{
access_token: useTokenStore.getState().accessToken,
'Content-Type': 'multipart/form-data',
},
[
...fileData,
// elements without property `filename` will be sent as plain text
{name: 'org_id', data: String(org_id)},
{name: 'ans', data: String(userAns)},
{name: 'remark', data: String(userRemark)},
{name: 'img', data: String(userImg)},
],
);

App crushes on bad request and network error using fetch in react-native

My react native app crashes in .apk when fetch returns a bad request or network error
Below is the fetch function:
try {
const reponse = await fetch(
'http://example.com',
{
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body
},
);
if (reponse.ok) {
const data = await reponse.json();
console.warn('Success response', data);
return navigation.navigate('different', {
token: data.token,
memberNo: data.user.memberno,
});
} else {
setStatus('Incorrect Details entered');
// console.warn('Failed response', reponse);
}
} catch (error) {
setStatus('Network request failed connect to the internet');
// console.error('CATCH Error', error);
}
}```
First check you API response may be its return something null or undefined and you used that in your screen.
e.g when we use flatlist and pass undefined and null then the apk crash so focus on your data format

Network Error when sending file in react native with axios

I am trying to send a file to a nodejs server from react native using axios, this is my code:
const createFormData = (file) => {
const data = new FormData();
data.append('message', text);
data.append('receiver',doctorid);
if(file !== ''){
data.append('file', {
type: file.type,
uri: file.uri,
name: file.name.replace(/\s/g,'')
})
}
return data;
}
const onSend = async() => {
const newMessages = [...messages]
newMessages.push({"sender": currentuserID, "id": 339, "message": 'sending...', "attachment": '', "receiver": doctorid, "type": 0},)
setMessages(newMessages)
const token = await AsyncStorage.getItem('token');
const data = createFormData(singleFile)
await appApi.post('/chats', data, {
headers: { 'Authorization': 'Bearer ' + token }
}).then(()=>{
socket.emit('sendmessage', text, (err) => {
messageInit()
});
})
.catch(err => console.log(err.message))
}
This code works perfectly if there's no image attached, but ones there's an image attached, I get the network error message immediately.
For a little bit of troubleshooting, I tried sending request to my local machine, using ngrok. From ngrok, I realized the request wasn't sent at all to the url. So it just fails immediately, without the request been made to the url.
Anyone with solution to this.
I'm testing on an android emulator
send using formdata
try this
let formData = new FormData();
let imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

Getting error during uploading a video in react native

I am fetching video from mobile using react-native-image-picker and uploading it to the server by using the fetch method. Don't know what I am doing wrong?
constructor(props){
super(props);
this.state = {
isLoading:true,
isModalVisible: false,
isOptionVisible:false,
avatarSource:"",
chapname:'',
chapdesc:''
}
};
var formData = new FormData();
formData.append('name', 'video name');
formData.append('desc', 'video description');
formData.append('file', {uri: this.state.avatarSource, name: this.state.avtarname.fileName, type: 'video/mp4'});
fetch(api, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type' :'multipart/form-data',
'Authorization': `JWT ${teacher_token}`
},
body: formData
})
and here is the response when I pick a video from phone
{path: "/storage/emulated/0/DCIM/Camera/VID_20200306_172706.mp4", uri: "content://com.miui.gallery.open/raw/%2Fstorage%2Fe…ted%2F0%2FDCIM%2FCamera%2FVID_20200306_172706.mp4"}
the error I getting is a network request failed. Here is the error which gets on the console
Fetch Error TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (E:\eshikshaserver\node_modules\whatwg-fetch\dist\fetch.umd.js:473)
at XMLHttpRequest.dispatchEvent (E:\eshikshaserver\node_modules\event-target-shim\dist\event-target-shim.js:818)
at XMLHttpRequest.setReadyState (E:\eshikshaserver\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574)
at XMLHttpRequest.__didCompleteResponse (E:\eshikshaserver\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388)
at E:\eshikshaserver\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:501
at RCTDeviceEventEmitter.emit (E:\eshikshaserver\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (E:\eshikshaserver\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436)
at E:\eshikshaserver\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111
at MessageQueue.__guard (E:\eshikshaserver\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384)
at MessageQueue.callFunctionReturnFlushedQueue (E:\eshikshaserver\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110)
I know something I am missing but can not find it. Stucked on it.

Android: Network Request Failed when trying to upload image with fetch

I'm trying to upload an image from storage to a restful API but I keep getting Network Request Failed on Android (which means the request doesn't even go through), haven't checked on iOS because I don't need that part yet. API is already working and has been tested with Postman.
The React Native code is:
body.append('vehicles',{
resource_id: 2,
resource: 'vehicles',
cat_file_id: fileId,
active: 1,
vehicles: photo, //<- photo value below
name: 'vehicles',
type: 'image/jpeg'
})
fetch(`${BASE_URL}/files`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
Accept: "*/*",
Authorization: 'Bearer '+auth
},
body: body
}).then(response => response.json())
.then(response => {
console.log('IMAGE RESPONSE', response)
})
.catch(error => console.log('ERROR', error))
The photo value looks like file:///storage/emulated/0/DCIM/...
The response:
ERROR TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (fetch.umd.js:473)
at XMLHttpRequest.dispatchEvent (event-target-shim.js:818)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:574)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:388)
at XMLHttpRequest.js:501
at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
at MessageQueue.__callFunction (MessageQueue.js:436)
at MessageQueue.js:111
at MessageQueue.__guard (MessageQueue.js:384)
at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:110)
On Postman the request looks something like this:
Already tried:
Removing Accept header
Changing Accept value to 'application/json'
Removing file:// from the image url
Added android:usesCleartextTraffic="true" to the manifest
Already checked:
No values are null or undefined
There is a working internet connection, all other network requests on the app are working fine
The Auth is correct
React Native version is 0.61.5
I found one missing line in your code let formData = new FormData();. but not sure is that the exact issue here.
By the way here is a sample working code from one of my project, and I customized it with your context.
Add your authentication
replace ImageURI with image path and URL_SAVE_IMAGE endpoint url
const newImage = {
resource_id: 2,
resource: 'vehicles',
cat_file_id: 1,
active: 1,
vehicles: ImageURI,
name: "my_photo.jpg",
type: "image/jpg",
};
let formData = new FormData();
formData.append("vehicles", newImage);
return fetch(URL_SAVE_IMAGE, {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formData
}).then(response => response.json());
it should work!
What is your fetch(${BASE_URL}/files` backend server .. This usually happens when trying to connect to the backend api on the localhost machine.. Even if you use the IP address of the localhost, it still persists, so it is better to use online server for testing or just use ngrok(https://ngrok.com/) to serve your backend localhost via internet.
in gradle.properties change the flipper version to 0.47.0
try with Xhr, it's working as expected!
const URL = "ANY_SERVER/upload/image"
const xhr = new XMLHttpRequest();
xhr.open('POST', url); // the address really doesnt matter the error occures before the network request is even made.
const data = new FormData();
data.append('image', { uri: image.path, name: 'image.jpg', type: 'image/jpeg' });
xhr.send(data);
xhr.onreadystatechange = e => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('success', xhr.responseText);
} else {
console.log('error', xhr.responseText);
}
};
Nothing worked for me except using the Expo FileSystem uploadAsync
uploadImage = async ({ imageUri } }) => FileSystem.uploadAsync(
apiUrl,
imageUri,
{
headers: {
// Auth etc
},
uploadType: FileSystem.FileSystemUploadType.MULTIPART,
fieldName: 'files',
mimeType: 'image/png',
});
Note - imageUri in format of file:///mypath/to/image.png
Happy days!