Tony Lee Tony Lee - 12 days ago 5
Node.js Question

How to respond with an image on express route

My app is structured using express-generator and I have thrown a thumbnail image into the public folder and now I have this route:

router.get('/thumbnail', function(req, res){
res.sendFile('public/thumbnail.jpg');
});


I want the image to be shown/sent on to the browser so I get to put this link onto the meta tag and the thumbnail would appear in Facebook shares but this isn't working and instead gets me my apps error page. Also I have tried setting the header type to
image/jpg
but it also didn't work and rendered an empty
img
tag.

Answer

Guessing that you have something like this:

    const publicPath = express.static(join(__dirname, '../public'));
    app.use('/public', publicPath);

You can do:

    app.get('/thumbnail', function(req,res){        
        res.send('<img src="/public/img/thumbnail.jpg" />');
    });

This will render the image.

Comments