Home > Net >  axios vs fetch throwing error on file upload
axios vs fetch throwing error on file upload

Time:06-06

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

   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: ''
    })
  }
}

CodePudding user response:

For image upload you not use JSON.stringify(data).You can try with formData and append an image file with form data.

var formdata = new FormData();
formdata.append("image", data);

CodePudding user response:

Did you check that

const filename = request.payload.filename

exists?

Is the key really payload? The following does not make any changes to your code:

.then((payload) => {
  return payload;
})
  • Related