axios response.blob is not a function
Asked Answered
H

1

6

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();
        })
Hutchins answered 16/8, 2021 at 16:47 Comment(8)
Use res.arrayBuffer() instead of res.blob().Phineas
Set responseType: 'blob' to axios options, then get response by res.data. check this answerStratovision
@HassanImam I tried using res.arrayBuffer() but I get an error saying res.arrayBuffer() is not a function, similar to res.blob()Hutchins
@AminTaghikhani I just tried your suggestion, but in firebase storage, the image is uploaded as an "octet-stream/application" filetype, and the size of the uploaded file is 9bytes as opposed to the original 130+kb size.Hutchins
Why are you not storing the blob on the server where it's at and returning the download url?Wellgrounded
@OluwafemiSule I could, but I'm using Firebase's cloud storage service and its sdk allows for a much easier upload on the client side.Hutchins
Did you find a solution for this. I am having the same problem.Midship
@BuwanekaSudheera No I couldn't find a good solution. Instead, I ditched axios and decided to use fetch just for that particular api. Fetch works with res.blob without any problems.Hutchins
D
17

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

Deyoung answered 13/5, 2022 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.