【问题标题】:React Native Android device throws error for Fetch while uploading a json file : TypeError: Network request failedReact Native Android 设备在上传 json 文件时为 Fetch 抛出错误:TypeError: Network request failed
【发布时间】:2019-03-07 07:36:35
【问题描述】:

我已经编写了代码来调用 Fetch 方法将 Json 文件发布到 IPFS 。 我正在本地编写成功的 JSON 文件,但是后来当我使用 FORMDATA 调用 POST 方法将 json 文件写入 IPFS 时,它失败了。 相同的代码在 iOS 上运行良好。不知道安卓有什么问题。

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

我使用的是 Android 8.0 版、Reactnative 0.57 版和“react-native-fs”:“^2.13.3”。 有人可以建议另一种进行网络调用的方法。不能使用本机代码,因为此代码在 JS 库中。请提供您宝贵的反馈。 下面是代码 sn-p :

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)

【问题讨论】:

    标签: android react-native fetch


    【解决方案1】:

    我通过使用 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
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多