Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  96] [ 5]  / answers: 1 / hits: 12888  / 4 Years ago, thu, march 19, 2020, 12:00:00

I want my the /image of my app to return a random image, how can I do that?



app.js:



const app = express();

app.get('/image', async (req, res) => {
const url = 'https://example.com/images/test.jpg';
res.send(/**/); // How do I send the image binary data from the url?
});





index.html



In HTML, this image actually shows the content of the image https://example.com/images/test.jpg



<img src=https://my-app.com/image />

More From » node.js

 Answers
17

We have the same problem, and this is my solution for this using request package, so you have to yarn add request or npm i request first.
your code should be like this


const request = require('request');
const express = require('express');
const app = express();

app.get('/image', async (req, res) => {
const url = 'https://example.com/images/test.jpg';

request({
url: url,
encoding: null
},
(err, resp, buffer) => {
if (!err && resp.statusCode === 200){
res.set("Content-Type", "image/jpeg");
res.send(resp.body);
}
});
});

[#4446] Monday, March 16, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
austynp questions
;