Search code examples
javascriptnode.js

I want to send Buffer Object as response from API


I have an image file that is created on my backend(node) and I am trying to send that to the front end to display. I'm not exactly sure how to manage the data but when I console the variable that's holding the file I get this:

Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e2 02 28 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 ...

I'm making a GET request from the front end and I want to be able to grab the image that's created and then displayed on the frontend. Is something like this possible?

The other option I've come up is to use a database to store the file but I'm trying to avoid a db.


Solution

    1. Convert Buffer Object to Base64 in your backend:
    Buffer.from("Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e2 02 28 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 ...").toString('base64')
    
    1. Put String in src attribute of img tag:
    <img id="image" src="" />
    
    fetch(YOUR_BACKEND_URL)
      .then(response => response.json())
      .then(data => {
        document.getElementById('image').src = `data:image/png;base64, ${data.message}`
    });