Home > Blockchain >  Display image from API in JS/Vue.js 3
Display image from API in JS/Vue.js 3

Time:04-06

I am trying to display an image that is returned via API but without success.

In the Postman it is displayed normally:

postman

But when I do the console.log of the returned data the following is displayed:

console

How do I convert this to a valid string for the src?

Thanks!

CodePudding user response:

It's very likely that in your fetch you are trying to parse json, while you should parse as blob.

fetch(url, options)
.then(res => res.blob())
.then(res => //do your thing here)
.catch(error => console.log(error))

CodePudding user response:

Since I am using Axios, it was necessary to change the response type to "blob":

try {
    const response = await api.post(
      "...",
      {
        ...
      },
      {
        responseType: "blob"
      }
    );

    return URL.createObjectURL(
      new Blob([response.data], { type: "image/png" })
    );
} catch (error) {
    console.error(error);
}

So all you had to do was include the return in the SRC attribute of the image.

  • Related