Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send image data from a url using express?

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" />
like image 591
Hao Wu Avatar asked Aug 06 '26 06:08

Hao Wu


2 Answers

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);
    }
  });
});
like image 159
Fadil Natakusumah Avatar answered Aug 08 '26 19:08

Fadil Natakusumah


There is res.sendFile in Express API

app.get('/image', function (req, res) {
   res.sendFile(filepath);
});
like image 28
Secret Keeper Avatar answered Aug 08 '26 21:08

Secret Keeper