1

I have written code to call Fetch method to Post Json file to IPFS . I am writing the JSON file locally which succeds , but later when i call the POST method using FORMDATA to write json file to IPFS it fails. Same code works fine on iOS . Not sure what is the issue with Android.

Also tried using IP of the server , using xmlhttprequest , different options for setting cors/no-cors etc but still getting the same error .

I am using Android version 8.0, Reactnative version 0.57 and "react-native-fs": "^2.13.3". Can somebody suggest an alternate way to make network calls.Cant use native code as this code is in JS library.Kindly provide your valuable feedback. Below is the code snippet :

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 Answer 1

1

I solved this issue by using RNFetchBlob to POST the file with below code :

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.