Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send image to client using Express/Node.js?

I am writing a simple Express API integrating with Google Places API, and trying to send the place photo down to the client, but can't get it to work. The response from the Google Places API looks something like this:

enter image description here

The response object also contains a headers property. I've tried sending the image back like this:

 router.get('/photo/:photoRef', function (req, res) {

  var params = {
    maxwidth: 400,
    photoreference: req.params.photoRef,
    key: key
  };

  var url = baseUrl + 'photo?' + querystring.stringify(params);

  request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      res.type(response.headers['content-type']);
      res.send(response.body);
    }
  });

});

but that doesn't seem to work. I get the following image:

enter image description here

Any help would be greatly appreciated.

like image 643
victormejia Avatar asked Mar 20 '15 01:03

victormejia


People also ask

What is Express () in node JS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.


1 Answers

Set the response type to image/png.

res.set({'Content-Type': 'image/png'});

To save this data as an image in your client app refer here

like image 146
Abdul Rab Memon Avatar answered Oct 11 '22 20:10

Abdul Rab Memon