I am making a POST request to "Cloudinary" server to upload an image and sending formdata using axios in react-native. The whole process is working fine on iOS but on android i am getting "Network Error".
I am using axios 0.18.0 and stuck on this from last 3 days. Someone please help me.
This issue has been faced by many people but there is no solution so far.
My code:
` var photo = {
uri: image.sourceURL,
type: image.mime,
name: image.filename,
};
var formData = new FormData();
formData.append('file',photo);
formData.append('upload_preset','abcde');
axios({
url:'https://api.cloudinary.com/v1_1/abcde/upload',
method:'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded'
},
data:formData
}).then(function(response){
}).catch((error) =>{
//Network error comes in
});
`
Have you tried with CORS headers ?
Please send the entire error, and maybe a screen of the response headers (Browser)
Not yet. Can you point me in that direction?
Just to add one thing: My GET request are going fine just POST requests are not working on android.
For example :
axios({
url:'https://api.cloudinary.com/v1_1/abcde/upload',
method:'POST',
headers:{
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
'Access-Control-Allow-Headers': 'Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type',
'Accept': 'application/x-www-form-urlencoded',
'Content-Type':'application/x-www-form-urlencoded'
},
data:formData
})
Just tried and it is still giving same error - " Error: Network Error".
In the console log i am getting this:
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:567)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:397)
at XMLHttpRequest.js:503
at RCTDeviceEventEmitter.emit (EventEmitter.js:179)
at MessageQueue.__callFunction (MessageQueue.js:351)
at MessageQueue.js:116
at MessageQueue.__guardSafe (MessageQueue.js:314)
You correctly entered the Cloudinary API KEY ?
You displayed something on the catch ??
Yes. Same code is able to upload image on cloudinary without any issue. The console error is handled at catch of axios.
Take a loot at : https://github.com/facebook/react-native/issues/10404
I have already checked out this link but none of the answers seems to work :|
@msouidi309 i have fixed it by making some underlying changes in axios (though this is not the best way). Thanks for your support. I really appreciate it.
@vishal2947 I'm stuck at the same step too, could you explain what you have changed with axios to get it to upload the file if it's not too much to ask? Thank you.
@vishal2947 I'm experiencing an issue similar to what you describe. What were the steps you took to solve it?
We've gotten around this by keeping the 'Content-Type':'application/x-www-form-urlencoded'
headers, but using a string in the formdata format, instead of FormData
, like:
const body = { some: 'data', bla: 'asdf' };
// key=value&otherkey=value is what FormData produces
const data = Object.entries(params)
.map((pair) => `${pair[0]}=${pair[1]}`)
.join('&');
axios({
url:'https://api.cloudinary.com/v1_1/abcde/upload',
method:'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded'
},
data,
}).then(function(response){
try to change the adb port with this command:
adb reverse tcp:8880 tcp:8880; adb reverse tcp:8081 tcp:8081; adb reverse tcp:8881 tcp:8881
any update on this? or at least a workaround?
axios in react native uses the nodejs implementation as an adapter and it's working fine in both android and ios but in android I don't know why you should add the correct image/file type to your form data or it will raise "Network Error" try this formData.append('file', {...photo,type:"image/jpeg"});
or png
Hello guys,
I think this can help us to solve the problem, I was the same problem in my project and I add the test domain on react_native_config.xml on android studio, follow print bellow:
After that add IP 192.168.0.9 (my API URL) my application works fine in Android.
@marcogorak I don't have that file in my react native project, and adding it manually didn't seem to change anything. Was that file already there or did you create it manually?
For those who's struggling in this issue:\
After finding a ton of solutions on internet I was still stuck in this problem, some people say it's about the network problem (android prevent HTTPS,..), some others say we need to add multipart/form-data
in header along with the request sent to server. I tried all but didn't work
The thing is when I put the file inside formData
it breaks, if I comment it and just send for example a number, it's fine.
THE SOLUTION is:
on Android you need to specify the file path with file://
as prefix. So do like this:
const audio = {
uri: 'file://' + this.recorder.fsPath,
type: 'video/mp4',
name: filename
}
God bless you! ❤️
so I've been working on this issue for a week and came up with this solution:
let uploadData = new FormData();
uploadData.append('type', type)
for (let i = 0; i < files.length; i++) {
uploadData.append('images[]', files[i]);
}
axios({
method: 'post',
url: API_URL + '/uploadJobcardPhoto',
data: uploadData,
headers: {
"Content-Type": "multipart/form-data",
"cache-control": "no-cache",
"Postman-Token": "8bdabec9-2814-4e70-85e9-a43a9f30b174" },
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
})
.then(function (response) {
console.log('response',response.data)
})
.catch(function (error) {
console.log(error);
});
I had the same issue, Adding type: 'image/jpeg',
to the file attribute of the formData fixed it.
const formData = new FormData();
formData.append('file', {
uri: pictureUri,
type: 'image/jpeg',
name: 'profile-picture'
})
same problem
type: 'image/jpeg'
solved this issue for Andriod
Thanks @cesar3030.
Was a mime type problem.
For those who's struggling in this issue:
After finding a ton of solutions on internet I was still stuck in this problem, some people say it's about the network problem (android prevent HTTPS,..), some others say we need to addmultipart/form-data
in header along with the request sent to server. I tried all but didn't workThe thing is when I put the file inside
formData
it breaks, if I comment it and just send for example a number, it's fine.THE SOLUTION is:
on Android you need to specify the file path withfile://
as prefix. So do like this:const audio = { uri: 'file://' + this.recorder.fsPath, type: 'video/mp4', name: filename }
God bless you! ❤️
awesome, bro!
In my case, I was passing number value, which was causing it.
like,
const body = {
user_id: 1, // <----
}
While converting it to form-data, we have to convert it into a string.
Object.keys(body).map(key=>{
formData.append(key, body[key].toString());
});
I had the same issue, Adding
type: 'image/jpeg',
to the file attribute of the formData fixed it.const formData = new FormData(); formData.append('file', { uri: pictureUri, type: 'image/jpeg', name: 'profile-picture' })
This is my case also. However, you need to notice your uri part, as it can be file:// or file:/. Test to see which one suits you. And lastly, you need to specify all three keys: uri, type, and name. I have solved my problem, hopefully this may help someone in the future.
I have tried all the above-mentioned solutions.
let s = JSON.stringify({ uri: file.path, name: "anyName", type: "image/jpeg" });
//file.path ="file:///storage/emulated/0/Pictures/d308f9a0-d14f-483c-8236-51f9d097fcc3.jpg"
axios
.post(
"http://10.20.10.119:5000/.../.../image",
data,
{
headers: {
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, PUT, OPTIONS, DELETE",
"Access-Control-Allow-Headers": "*",
Accept: "*",
Authorization:
"Bearer Token"
}
}
)
.then((data) => {
console.log("Hurrey success");
return data;
})
.catch(err => console.log(err));
It doesn't go to catch but on server side on express if I say req.file
is undefined in both the cases.
However, body size is different in both cases:
req.body.toString().length
)here is my controller
app.post("/contacts/:id/image/", authMiddleware, (req, res, next) => {
const BusBoy = require('busboy');
const path = require('path');
const os = require('os');
const fs = require('fs');
const busboy = new BusBoy({ headers: req.headers });
let imageFileName;
let imageUrl;
let imageToBeUploaded = {}
console.log("Image Upload", req.headers, "file is ", req.file, " body ::::: ", req.body);
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
const imageExtension = filename.split(".")[filename.split(".").length - 1];
imageFileName = `${Math.round(Math.random() * 1000000000000).toString()}.${imageExtension}`;
const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ');
});
busboy.on('finish', () => {
admin
.storage()
.bucket()
.upload(imageToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype
}
}
})
.then(() => {
imageUrl = `https://firebasestorage.googleapis.com/v0/b/${
firebaseWebCredentials.storageBucket
}/o/${imageFileName}?alt=media`;
//code....
})
.catch((err) => {
console.error("Error occured while file upload", err);
return res.status(500).json({ error: err });
});
});
busboy.end(req.rawBody);
})
My busboy.on file only invoke with Axios web, not with react-native Axios. (it consider req as field and go inside field)
Field [image]: value: {"uri":"file:///storage/emulated/0/Pictures/2e98c3eb-da9a-47e6-a9df-bf0cc159ef16.jpg/","name":"dsfsdfsdfsdf","type":"image/jpeg"}
I try to use different solutions but I don't understand what is the problem
i am having the same issue , i am unable to send formdata from my android device ,same code works fine on iOS .
code below :
let formdata = new FormData();
formdata.append("formData", {uri: source, name: response.fileName, type: 'video/mp4'})
axios.post(BASE_URL + '/api/testupload', formData, {
headers: {
'authorization': "Bearer " + jwt_token,
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
console.log(res);
console.warn(res.data.videoPath);
})
.catch(err => alert("error: " + err))
i got this error,
i can see that error says
XMLHttpRequest.xhr.onerror (blob:http://_localhost_:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:26873:18)
here do i need to replace _localhost_ with IP ? if yes then how ?
Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:26873:18)
at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:28680:27)
at XMLHttpRequest.setReadyState (blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:28433:20)
at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:28260:16)
at blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:28370:47
at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:6075:37)
at MessageQueue.__callFunction (blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:2531:44)
at blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:2288:17
at MessageQueue.__guard (blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:2485:13)
at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/77190d04-0165-47a6-adc6-0e8fd408f1bc:2287:14)
"react-native": "0.59.9",
"react-native-axios": "^0.17.1",
help will be appreciated.
+1 .
This exists for both fetch and axios.
Well none of the solution above works which are nothing but some silly mistakes everyone did.
Hoping for a solution which is real.
+1 .
This exists for both fetch and axios.
Well none of the solution above works which are nothing but some silly mistakes everyone did.Hoping for a solution which is real.
@kunal886496 Well I agree that it's possible that we made some mistakes but that doesn't make sense if the same setup works for react and not work for react-native.
What fixed for me was adding a 'name' field like this:
function upload (data, images, token) {
const formData = new FormData();
formData.append('data', data);
images.forEach((image, i) => {
formData.append('images', {
...image,
uri: Platform.OS === 'android' ? image.uri : image.uri.replace('file://', ''),
name: `image-${i}`, // THIS
type: 'image/jpeg', // it may be necessary in Android.
});
});
const client = axios.create({
baseURL: 'http://localhost:3001',
});
const headers = {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
}
client.post('/items/save', formData, headers);
}
+1 .
This exists for both fetch and axios.
Well none of the solution above works which are nothing but some silly mistakes everyone did.Hoping for a solution which is real.
Same issue, same hope. Why is this issue closed?
+1
On Fri, May 15, 2020, 11:59 Wicat21 notifications@github.com wrote:
+1 .
This exists for both fetch and axios.
Well none of the solution above works which are nothing but some silly
mistakes everyone did.Hoping for a solution which is real.
Same issue, same hope. Why is this issue closed?
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/axios/axios/issues/1567#issuecomment-629054715, or
unsubscribe
https://github.com/notifications/unsubscribe-auth/AGYT2BSOIICMI3GUNVLVOLTRRTOK5ANCNFSM4FCAAG4A
.
Issue is persistent on react native, issue should be re-opened, none of the above solutions work. I think we need more mature approach in debugging, where can I see exact issue because of which my request is never sent out to server?
On emulator i saw something like bad file descriptor, but I usually use real device, that doesn't show such issue when i inspect err.request
If you are using flipper, it may help - https://github.com/facebook/react-native/issues/28551#issuecomment-624347067
Most helpful comment
I had the same issue, Adding
type: 'image/jpeg',
to the file attribute of the formData fixed it.