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 = '.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 .jpg
<img src="" />
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./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./images/test.jpg
<img src="https://my-app./image" />
Share
Improve this question
asked Mar 19, 2020 at 9:33
Hao WuHao Wu
20.8k6 gold badges36 silver badges77 bronze badges
3
-
You need
res.sendFile(...);
for that. And you need to pick a random file, not a url. – user5734311 Commented Mar 19, 2020 at 9:37 - The thing is, all the images are from the internet, not serving on my server. Is it possible? @ChrisG – Hao Wu Commented Mar 19, 2020 at 9:38
-
In that case you can try
res.redirect()
, not sure if it works for images though. If not, you'll have to download the image on the server, then send back the file. Or maybe pipe the stream somehow. – user5734311 Commented Mar 19, 2020 at 9:41
4 Answers
Reset to default 7We 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./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);
}
});
});
There is res.sendFile
in Express API
app.get('/image', function (req, res) {
res.sendFile(filepath);
});
const express = require("express");
const https = require("node:https");
const app = express();
const port = 3000
app.get("/", function(req, res){
const url = "https://api.openweathermap/data/2.5/weather?q=Paris&units=metric&appid=65441206f989bc53319e2689fccdc638";
https.get(url, function(response){
response.on("data", function(data){
const weatherData = JSON.parse(data)
const icon = weatherData.weather[0].icon
const imageUrl = "http://openweathermap/img/wn/" + icon + "@2x.png"
res.write("<img src=" + imageUrl + " ></img>")
res.send();
})
});
})
You can save all such image links in json or any of your choice data file and get from them randomly and forward and pass them through variable in response. Like: res.send(imgURL: 'https://example./images/test.jpg');
or you can pass url variable in init.