Displaying an Image on a Web Page using Node.js and Express

Serving Static Files

To display images or any other static files (CSS, JavaScript, etc.), you need to instruct Express to serve a static directory. Let’s create a folder called public:

mkdir public

Configuring Express for Static Assets

Update your app.js to serve static files from the public directory:

// Serve static files from the 'public' folder
app.use(express.static('public'));

Now, any files inside the public directory can be accessed directly by their path.

Displaying the Image in Your EJS Template

Modify your index.ejs to include an image:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><%= title %></title>
  <style>
    /* Basic styling for the image */
    .responsive-img {
      max-width: 100%;
      height: auto;
    }
  </style>
</head>
<body>
  <h1><%= message %></h1>
  <p>Welcome to your EJS templated page!</p>
  <!-- Display the image -->
  <img src="/example.jpg" alt="Example Image" class="responsive-img">
</body>
</html>

Here, the src="/example.jpg" path points to the file in your public folder. This setup ensures that your image loads correctly on your web page.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top