Search code examples
node.jsreactjsaxiosblobarraybuffer

axios response.blob is not a function


I am trying to pass a blob with the type of "image/jpeg" from nodeJS to react. In the nodejs end, I pass the data using arraybuffer and on the react end, I try to retrieve it using res.blob which should usually convert the data back. The thing is axios is returning an error saying res.blob() is not a function. How do I retrieve it in the react end then? Any response will be most appreciated and I apologize if I haven't described my issue well enough.

This is my code in nodejs

  res.type(blob.type);
  blob.arrayBuffer().then((buf) => {
    res.end(Buffer.from(buf));
  });

And this is my code in react.

    axios
    .post(imageUrl)
    .then((res) => {
      return res.blob();
    })
    .then((blob) => {
      storageRef
        .child(path + filename)
        .put(blob)
        .then(function (snapshot) {
          return snapshot.ref.getDownloadURL();
        })

Solution

  • When using axios you don't need to use blob(), just set responseType: 'blob' to axios options. e.g.

    axios.get(PF + userCreds.user.profilePic, {responseType: 'blob'})
    

    and after that in the .then() function instead of

    .then(axios.spread((...responses) => {
        responses.map((res) => (
            console.log(URL.createObjectURL(res.data.blob())
        ))
    }))
    

    do that

    .then(axios.spread((...responses) => {
        responses.map((res) => (
            console.log(URL.createObjectURL(res.data))
        ))
    }))
    

    the result is the same as fetch