Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - React Native-我无法通过fetch发送任何FormData(React Native - I cannot send any FormData with fetch)

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.

(我试图将图像和一些描述从我的React Native应用程序发送到Node Rest Api,但它从未到达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] .

(当我发送图像时,访存将引发错误: [TypeError:网络请求失败] 。)

And no request is received by my node server.

(我的节点服务器未收到任何请求。)

I've tried sending a FormData only with strings, something like:

(我试过仅使用字符串发送FormData,例如:)

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 .

(我使用的是Expo 版本35.0.0和React Native的版本0.59.8 ,并且正在实际的Android设备中测试该应用。)

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.

(请有人告诉我我做错了什么,我一直在寻找答案,但是我没有找到任何适合我的方法。)

  ask by KOseare translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...