0

I have an image API running from a home server, and I'm building a cloud-hosted page that grabs the image in backend and shows it, for a layer of abstraction.

Here's what I'm trying to do:

index.js

var express = require('express');
var router = express.Router();


router.get('/', function(req, res, next) {
     // some logic to grab the image and pass it to the HTML page
     // var image = fetch("myimageapi.com") 
     // ?????
  res.render('index', {page:'Home', menuId:'home'});
});

and display it with <img id="myimage">

Or maybe it would be better to:

router.get('/', function(req, res, next) {         
  res.render('index', {page:'Home', menuId:'home'});
});
router.get('/image', function(req, res, next) {
     //fetch image
});

and <img src="mywebsite.com/image>

I really have no idea how one would go about doing this in node, I am coming from python and this is all very scary

  • So you don't want to use the actual image URL in the HTML, is that correct? – Phil Aug 17 '22 at 02:48
  • @Phil exactly. I want the image to be fetched in the backend, and then displayed as if it were hosted on the server itself. – Cory Future Aug 17 '22 at 02:53
  • Would a [proxy](https://stackoverflow.com/a/32756976/283366) work for you? – Phil Aug 17 '22 at 02:54
  • Express provides a download() function. https://www.geeksforgeeks.org/how-to-download-a-file-using-express-js/. If I understand it correctly. You download the picture onto your server. Then inserting the file path as a 'src' attribute on your page. If you don't need to download the image. You could point to the original file address, too. Keep in mind you have to redirect the express request to the original host in that case. – kiroshiro Aug 17 '22 at 11:28

1 Answers1

0

I solved it, just had to come back with a fresh brain:

app.get('/', (req, res) => {
    res.render("index")
})

app.get('/image', async (req, res) => {
    const url = 'example.com/image.png';
  
    request({
      url: url,
      encoding: null
    }, 
    (err, resp, buffer) => {
      if (!err && resp.statusCode === 200){
        res.set("Content-Type", "image/jpeg");
        res.send(resp.body);
      }
    });
});

In index.ejs: <image src='/image'> calls the image route and pulls the image as if it were a static file. I feel like it would be cleaner to pass it directly to the page, but this solution works so I'm running with it.