Yahoo
Yahoo

Reputation: 568

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>

Upvotes: 1

Views: 6701

Answers (3)

Necoo33
Necoo33

Reputation: 23

As i tested, in general of node.js using "path.join()" and "process.cwd()" functions for defining path of the files is best practice. you can serve static files such that middleware:

app.use(express.static(path.join(process.cwd(), "/images")));

This middleware serves the static files in the "/images" folder. process.cwd() function is make the path starts on root folder. it worked as expected in my deployment to the render.

Upvotes: 0

Sammy Berger
Sammy Berger

Reputation: 1

I was getting a similar issue, followed these steps, still wasn't getting anywhere. After trying everything, I changed my file from a .jpg to a .png and it started working.

(This isn't technically an answer to the post, but I wanted to put this out there for if other people are having this problem and I don't have the reputation to leave a comment)

Upvotes: 0

Kudos
Kudos

Reputation: 366

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'));

Upvotes: 4

Related Questions