Displaying an Image with Ejs in Node. Js/Express

Displaying an Image with Ejs in Node. Js/Express

I'm just trying to get setup with I know ejs isn't actual HTML and so I'm having a hard time just displaying a simple image. Can someone point me in the right direction?

Directory structure is:

  • myApp/server.js
  • myApp/views/index.ejs
  • myApp/logo.jpg

Right now I have

// index.ejs
<img src = "../logo.jpg" />

Am I going about this the wrong way? Thanks.

1

3 Answers

Static files in Express must go inside the directory specified in your static middleware. This is commonly ./public/.

For example, in your server.js you may have something like this:

app.use( express.static( "public" ) );

Each file inside this folder will be accessible from the root URL, so this will work:

<img src="logo.jpg" />
2

You have to assign app.use( express.static( "public" ) ); on app.js then don't forget the / as root:

<img src="/images/logo.jpg" />

the images folder should be in public folder:

- public/
  - images/
    - logo.png
- app.js

My js file was here c:/blog/index.js and image file c:/blog/views/image.js. And entered js file this code

app.use( express.static( "views" ) );

then in CSS added property

body {
background-image: url("./image.jpg"); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.