Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

axios vs fetch throwing error on file upload

I am using fetch instead of axios in my react project

my this method working fine with the axios to upload an image on the server

Upload image function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Upload customRequest={dummyRequest} className="upload-btn-container" onChange={onChange}>
  <Button className="btn custom-upload-btn">Upload Image</Button>
</Upload>
const uploadPicture = async (data) =>{
    const value = await getUploadPicture(data)
    if(value.value.data.status){    
        await addImage(value.value.data.data)
    }
}
const onChange = async (info) => {
for (let i = 0; i < info.fileList.length; i++) {
    const data = new FormData();
    data.append('file', info.fileList[i]);
    data.append('filename', info.fileList[i].name);
    setImgName(info.fileList[i].name)
    let value = await uploadPicture(data);
}

};

   return axios({
      method: 'post',
      url: `${NewHostName}/upload`,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('authToken')
      },
      data:data
    })
      .then(response => {
        return response
       
      }).catch(err => {
        console.log("err", err)
      })

whereas when I do same with the fetch it throws me error on the backend "Cannot read property of split of undefined"

return  fetch(`${NewHostName}/upload`, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: localStorage.getItem('authToken'),
    },
    body: JSON.stringify(data),
    // body :data
  })
    .then((res) => {
      return res.json();
    })
    .then((payload) => {
      return payload;
    })
    .catch((err) => {
      throw err;
    })

Not sure what is the reason behind this

this is my backend upload api

const handler = async (request, reply) => {
  try {
    const filename = request.payload.filename
    const fileExtension = filename.split('.').pop()
    AWS.config.update({
      accessKeyId: Config.get('/aws').accessKeyId,
      secretAccessKey: Config.get('/aws').secretAccessKey,
      region: Config.get('/aws').region
    })
    const s3 = new AWS.S3({
      params: {
        Bucket: Config.get('/aws').bucket
      }
    })
    const Key = `/${shortid.generate()}.${fileExtension}`
    const obj = {
      Body: request.payload.file,
      Key,
      ACL: 'public-read'
    }
    s3.upload(obj, async (err, data) => {
      if (err) {
        return reply({ status: false, 'message': err.message, data: '' }).code(Constants.HTTP402)
      } else if (data) {
        return reply({ status: true, 'message': 'ok', data: data.Location }).code(Constants.HTTP200)
      }
    })
  } catch (error) {
    return reply({
      status: false,
      message: error.message,
      data: ''
    })
  }
}

>Solution :

data is a FormData object.

In your original code you are lying when you say 'Content-Type': 'application/json'. Possibly Axios recognises that you’ve passed it a FormData object and ignores your attempt to override the Content-Type.

Your fetch code, on the other hand, says body: JSON.stringify(data) which tries to stringify the FormData object and ends up with "{}" which has none of your data in it.

  • Don’t claim you are sending JSON
  • Don’t pass your FormData object through JSON.stringify
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading