Search code examples
node.jsexpressejshtml-pdf

EJS page is not loading image


I am new to node.js and for this project I a mtrying to load image on ejs file. Images are inside public folder but still its not displaying images on .ejs file. If I call the project with the image url as localhost:3000/public/images/bmLogo.png , it displays the image. But if I call the url as src="/images/bmLogo.png" on ejs file, its not displaying the image. Is there a way I can display image on .ejs file?

Folder Path

-- views
   -report-template.ejs
-- public
   -images
     -bmLogo.png
app.js

View folder contains report-template.ejs on it and public folder which contains images/bmLogo.png .

App.js

let express = require("express");
let app = express();
let ejs = require("ejs");
let pdf = require("html-pdf");
let path = require("path");

app.use('/public/', express.static('./public'));

report-template.js

<!DOCTYPE html>
<html>
    <head></head>
    <body style="background-color:white; margin-top: -1.5%;">
            <div>
                <img src="/images/bmLogo.png" style="color:black;" alt="image name">
                <p>MIS Pictures</p>
            </div>
    </body>
</html>

Solution

  • So, you have this piece of code in app.js:

    app.use('/public/', express.static('./public'));
    

    The path will be /public/images/bmLogo.png, not /images/bmLogo.png So for the src attribute you can change it to /public/images/bmLogo.png. Or, you can do app.use(express.static("public")) instead of app.use('/public/', express.static('./public'));