Sunday, 14 May 2017

How to serve an image off of Redis using NodeJS and JQuery?

I'm trying to convert the image to base64 and storing in Redis cache and serve that base64 String on the corresponding request but I can't get it to work. I'm using axios to download an image using a get request and I'm converting it to a Base64 String.

Here's the code for that:

app.get('/img', (req, res)=>{
    console.log("Hello World!");
    axios.get("https://pbs.twimg.com/profile_images/655066410087940096/QSUlrrlm.png")
      .then((response)=> {
        var buff = Buffer.from(response.data).toString('base64');
        console.log("buff"+buff);
        res.end(buff);
    }).catch((error)=>{
        console.log("I got an error: "+error);
        res.end(error);
    });
});

On the frontend, I'm setting the src with the string returned from the backend (Saw it in some youtube tutorial)

   document.getElementById("mainImage").setAttribute('src', data);

where data is the result of a call to /img



via ishan Vadwala

No comments:

Post a Comment