Nacho Zve De La Torre
Nacho Zve De La Torre

Reputation: 364

How to properly serve a dinamic image with Node and Express?

I'm having many problems to achive what I'm trying:

I want to request an image from this URL http://tapas.clarin.com/tapa/1990/02/22/19900222_thumb.jpg and show it in the view but I'm getting this showned in the view instead:

enter image description here

What's the proper way of achieving what I want ?

This is my code:

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


var url = 'http://tapas.clarin.com/tapa/1990/02/22/19900222_thumb.jpg'

app.get('/', (req, res) => {
   rp(url)
  .then(image => res.set('Content-Type', 'image/jpeg').send(image))
  .catch(err => res.send(err));
})

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

Upvotes: 0

Views: 93

Answers (1)

Radu Luncasu
Radu Luncasu

Reputation: 1073

You're getting back a string from request-promise, not a buffer.Setting encoding: null, will get you a buffer which you can send back.

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


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

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

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

Upvotes: 1

Related Questions