在React Native中使用axios / fetch发送formData

时间:2020-01-14 17:02:22

标签: reactjs react-native axios fetch

从过去几天开始,我尝试使用axios / fetch发送带有必需标头的formData,但响应是网络错误。

任何人都可以分享一个代码片段,以了解如何使其在React Native中发挥作用。

谢谢

代码如下:

 var formdata = new FormData();
 var file = new File([base64Data], "ISDD_" + this.state.fileName, { lastModified: new Date().getMilliseconds() })

    formdata.append("file", file, this.state.fileName);
    formdata.append("folderName", this.state.folderName);
    formdata.append("userName", "myname@gmail.com");
    formdata.append("documents", documents);

  axios({
        url: url,
        method: 'POST',
        headers: {
            // "Content-Type": 'multipart/form-data',
            'enctype': 'multipart/form-data',
            'Cache-Control': 'sno-cache',
            'Pragma': 'no-cache'
        },
        data: formdata
    })
        .then((response) => {
            console.log(`1 ${response}`)
        })
        .catch((error) => {
            console.log(error)
        })

2 个答案:

答案 0 :(得分:0)

尝试一下:

 var formData = new FormData();  // make sure it is formData not formdata
axios({
        url: url,
        method: 'POST',
        headers: {
            "Content-Type": 'multipart/form-data',
        },
        formData
    })

答案 1 :(得分:0)

尝试这样

    var formdata = new FormData();
    formdata.append("file", file, this.state.fileName);
    formdata.append("folderName", this.state.folderName);
    formdata.append("userName", "myname@gmail.com");
    formdata.append("documents", documents);

axios({
    method: 'post',
    url: 'url',
    data: formdata,
    headers: {'Content-Type': 'multipart/form-data' }
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });