Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all articles
Browse latest Browse all 28480

React Native - I cannot send any FormData with fetch

$
0
0

I was trying to send an image and some description from my React Native app to a Node Rest Api but it never reaches the api. This is my code:

let formData = new FormData();

formData.append("imageFile", {
    uri: image.uri,
    type: "image/jpeg",
    name: filename,
});
/*
    image.uri is similar to this: "file:///data/user/0/host.exp.exponent/cache/ExperienceData
    /%2540anonymous%252FAppTest_v1-7f36da10-9f18-4a65-97f6-55d9c75f3998/ImagePicker/
    e54acf1b-5391-4db3-87e5-a8765decf3c5.jpg",
    and filename: "e54acf1b-5391-4db3-87e5-a8765decf3c5.jpg"
*/

formData.append("data", {fromApp: "true", userId: "testID123"});

//console.log(formData);
try{
    const response = await fetch(
        serverIp + "/manageFiles/almacenImagenes",{
            method: "POST",
            //headers: {'Content-Type': 'multipart/form-data'}, //doesn't work with or without this
            body: formData
        }
    );
    console.log("RESPONSE:",response);
    const resData = await response.json();
    console.log("resDATA:",resData);

}catch(err){
    console.log("ERROR:", err);
}

When I send an image, fetch throws the error: [TypeError: Network request failed]. And no request is received by my node server. I've tried sending a FormData only with strings, something like:

let formData = new FormData();
formData.append("something","abc123");

That is sent, but the body of the request is empty.

I also prove this:

const response = await fetch(serverIp + "/login", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        fromApp: true,
        email,
        password
    })
});

And it works correctly, but with that I cannot send an image.

I'm using Expo version 35.0.0 and React Native version 0.59.8, and I'm testing the app in a real Android device. Please someone can tell what I'm doing wrong, I've been looking for an answer everywhere but I haven't found anything that works for me.


Viewing all articles
Browse latest Browse all 28480

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>