I want my the /image of my app to return a random image, how can I do that?
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?
});
In HTML, this image actually shows the content of the image https://example.com/images/test.jpg
<img src="https://my-app.com/image" />
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);
}
});
});
There is res.sendFile in Express API
app.get('/image', function (req, res) {
res.sendFile(filepath);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With