React Native Android设备在上传json文件时抛出Fetch错误:TypeError:网络请求失败

时间:2019-03-07 07:36:36

标签: android react-native fetch

我已经编写了代码来调用Fetch方法以将Json文件发布到IPFS。 我正在本地成功地写入JSON文件,但是稍后当我使用FORMDATA调用POST方法以将JSON文件写入IPFS时,它将失败。 相同的代码在iOS上可以正常工作。不确定Android出现了什么问题。

还尝试使用服务器的IP,使用xmlhttprequest,用于设置cors / no-cors的不同选项等,但仍然出现相同的错误。

我正在使用Android版本8.0,Reactnative版本0.57和“ react-native-fs”:“ ^ 2.13.3”。 有人可以提出另一种进行网络呼叫的方法吗?由于此代码位于JS库中,因此无法使用本机代码。请提供宝贵的反馈意见。 以下是代码段:

justcall(valueToWrite){
  var path = RNFS.DocumentDirectoryPath + '/writeddo.json';
   //var path =  RNFS.LibraryDirectoryPath + '/writeddo.json';
    console.log("path",path);
    return new Promise((resolve, reject) => {
     // write the file
     RNFS.writeFile(path, valueToWrite,'utf8')
       .then((success) => {
         console.log('FILE WRITTEN!');
         let formdata = new FormData();
         formdata.append('file', {
           uri: path,
           name: 'writeddo.json',
           type: 'multipart/form-data'
         });
         console.log("formdata",formdata);
         console.log("IPFSADD Url",IPFSADD);

           fetch(IPFSADD, {
             method: 'POST',
             headers: {
              // 'Accept': 'application/json',
              'Content-Type': 'multipart/form-data',
             },
             //mode: "no-cors",  //, cors, *same-origin
             body: formdata
            })
            // .then((serviceResponse) => { return serviceResponse.json() } ) 
             .then((serviceResponse) => {
             console.log("Justcall response", serviceResponse);
                return this.deleteJsonFile(path).then(() => {
                    resolve(serviceResponse)
                })
                .catch((error) => {
                  console.error("Error while deleting the file error:", error)
                  reject(new Error(error))
                })
            })
           .catch((error) => {
            console.error("fetch error:", error)
            reject(new Error(error))
            })

        }) // Write File
       .catch((err) => {
         console.log("Error while writing file locally" +err.toString());
         reject(new Error(err))
       });
     }) //Promise
}



fetch error: TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394)
    at XMLHttpRequest.js:507
    at RCTDeviceEventEmitter.emit (EventEmitter.js:190)
    at MessageQueue.__callFunction (MessageQueue.js:349)
    at MessageQueue.js:106
    at MessageQueue.__guard (MessageQueue.js:297)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)

1 个答案:

答案 0 :(得分:0)

我通过使用RNFetchBlob通过以下代码POST文件来解决了这个问题:

uploadToIPFS(valueToWrite , filename ,name) {
  var path = RNFS.DocumentDirectoryPath + '/'+filename;
  console.log("path",path);
  let newValueToWrite =  Buffer.from(valueToWrite).toString('base64'); 
  return new Promise((resolve, reject) => {
    // write the file to IPFS
        RNFetchBlob.fetch('POST',IPFSADD, {
           'Content-Type' :  'application/json', //'multipart/form-data',
         }, [
          { name : 'name', filename : filename, data: newValueToWrite},
        ])
        .then(fetchBlobResponse => {
                  console.log("[IPFS backup] UPLOAD response!", fetchBlobResponse);
                  // Ensure we have `data` and a 200 response
                  if (
                    fetchBlobResponse.data &&
                    fetchBlobResponse.respInfo &&
                    fetchBlobResponse.respInfo.status === 200
                  ) {
                    console.log("[IPFS backup] UPLOAD SUCCESS!");
                    const responseData = JSON.parse(fetchBlobResponse.data);
                    console.log(
                      "[IPFS Response " +
                      responseData
                    );
                    resolve(fetchBlobResponse.data)
                  } else {
                    reject (new Error("[IPFS backup] Upload failure! HTTP status: " +
                        fetchBlobResponse.respInfo.status));
                  }
                });
    }) //Promise
}