Nacho Zve De La Torre
Nacho Zve De La Torre

Reputation: 364

How to send an image from the back end to the view with Node and Express?

I've got this piece of code making a request to the following URL and getting an image back as the response for the promise. Then I'm the login that image into the console which I assume it's working ok since it's in binary in the console.

var app = require('express')();
var http = require('http').Server(app);
var rp = require('request-promise');

var options = {
  uri: 'http://tapas.clarin.com/tapa/1990/02/22/19900222_thumb.jpg',

  headers: {
      'User-Agent': 'Request-Promise'
  },
  json: true // Json parse
};

rp(options)
  .then( res => {
    console.log(res)
  })
  .catch(function (err) {
      console.log(err)
  });

http.listen(3000, function(){
  console.log('listening on localhost:3000');
});

I need to instead of printing the image into the console, display it in the view, but I'm not able to do it, tried everything already.

What for?

I'm trying to make a robot that hits the URL with different params and bring the images back each time it hits the URL, then I need to do something else with each image.

This is my simple view.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Tapas Clarin</title>
</head>
<body>

    <div id="tapas">
        <!-- Acá quiero mostrar la imagen -->
    </div>
    <script src="./app.js"></script>
</body>
</html>

Upvotes: 0

Views: 926

Answers (3)

Nacho Zve De La Torre
Nacho Zve De La Torre

Reputation: 364

This is how I ended up doing it

const app = require('express')();
const http = require('http').Server(app);
const rp = require('request-promise');
const port = 3000;

const downloadImage = require('./downloadImage');

// Opciones de búsqueda
var options = {
    url: 'http://tapas.clarin.com/tapa/1990/02/22/19900222_thumb.jpg',
    encoding: null
}

// URL donde se hace el request
app.get('/', (req, res) => {
   rp(options)
  .then(image => {
      return res.end(image, 'binary');
  })
  .catch(err => res.send(err));
})

Upvotes: 1

Doudou G.
Doudou G.

Reputation: 29

Have you tried res.send(img) ?

For example if your API endpoint is /image then your code could be like:

app.get('/image', (req, res) => {
  rp(options).then(img => res.send(img))
    .catch(err => console.log(err));
});

Then on your Html client:

<img src="/image"/>

Upvotes: 1

Muhammad Aadil Banaras
Muhammad Aadil Banaras

Reputation: 1284

Create a simple API which is doing this, but giving in response image in base64, call that API from HTML page, and show it in img tag, as you can pass base64 directly in img tag, like this

<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD">

Upvotes: 1

Related Questions