Guide on navigating through various HTML pages with distinct parameters using Node.js (Express server)

Seeking assistance with a Node.js server that receives an ID as a query parameter. Each time a client connects with different parameters, I aim to serve them a unique HTML page containing a simple UI with 2 dynamic arrays. Everything seems to be working correctly except for the image not showing up. When I view the HTML page separately, the image displays properly. Any help would be appreciated.

Here is my server code:


var express = require('express');
var app = express();
const fs = require("fs");

// Helper function to read and serve html files 
// based on requested paths
function readAndServe(path, res) {
    fs.readFile(path, function (err, data) {
        res.end(data);
    })
}

// Set GET request path to receive id as query parameter
app.get('/:id', function (req, res) {
    console.log(req.params);

    // Map different ids to corresponding html files
    if (req.params.id == "screen=1")
        readAndServe("./1.html", res);
    else if (req.params.id == "screen=2")
        readAndServe("./2.html", res);
    else if (req.params.id == "screen=3")
        readAndServe("./3.html", res);
    else {
        res.end("Invalid request");
    }
});

app.listen(8080, () => { console.log("Server Listening on Port 8080") });

This is one of my HTML pages, all following the same logic but with different text and images:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport"
            content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
      <style>
         img{
         height: 500px;
         width: 450px;
         }
         h1{
         color: darkgreen;
         margin-top: 20px;
         font-family: Comic Sans MS, cursive, sans-serif;
         }
         .button{
         margin-left: 45%;
         }
      </style>
      <script>

         function changeImage() {
    var img = document.getElementById("img");
    img.src = images[x];
    x++;        
    if(x >= images.length) {
        x = 0;
    } 
   setTimeout("changeImage()", 6000);
   }

         function changeText() {
   var txt= document.getElementById("message");
   txt.textContent = text[y];
   y++;
   if(y>= text.length){
      y = 0;
   }
   setTimeout("changeText()", 6000);

   }


var text = [], y=0;
text[0] = "Message1";
text[3] = "Message2";
text[1] = "Message3";
text[2] = "Message4";
setTimeout("changeText()", 6000);
var images = [], x = 0;
images[0] = "image0.jpg"
images[3] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 6000);

      </script>
   </head>
   <body>
      <div class="container">
         <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-6">
               <h1 id="message">
                  Message2

               </h1>
               <img  id="img"
                     src="image1.jpg"  >
            </div>
            <div class="col-md-3"></div>
         </div>
      </div>
   </body>
</html>

Answer №1

To incorporate static files such as images and css files, utilize the express.static middleware.

1. Begin by creating a designated folder for your static files, for example 'public'.

2. Insert this line of code immediately after defining the app variable:

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

3. Organize all of your static files within this folder.

Keep in mind that once you have established the static folder, there is no need to include the folder name in your file paths. Instead of public/image1.jpg, simply use image1.jpg.

Additional information can be found here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to combine two tables in Sequelize using a one-to-many relationship

I'm currently working with two models: User and Foto. In my application, each User can have multiple fotos, and each foto is associated with only one user. My challenge lies in using the include function. I am able to use it when querying for the us ...

Secure Access: Passport.js User Verification & Authorization

Recently, I successfully developed my first User login and authentication system using Passport.js. While the system works as intended, I am struggling to fully comprehend the code itself despite reading numerous articles and examples online. I would great ...

What is the best way to incorporate an apostrophe into a string so that it can be displayed in a tooltip using jQuery

There is a text or string stored inside the 'data' variable, containing some texts with apostrophes. The issue I'm facing is that the tool tip is not displaying the text after the apostrophe symbol. How can I include all texts, including apo ...

Checking the opacity with an if/else statement, then adding a class without removing the existing class

This function is designed to check the opacity of the header, which fades out as a user scrolls down. If the opacity is less than 1, it disables clickability by adding the class "headerclickoff". However, there seems to be an issue with removing the clas ...

Troubleshoot variable using EJS

Is there a way to set a global variable in EJS that can show/hide specific elements across all views without the need to redefine it each time? I am using node.js/express/ejs for my project stack and would like to know the best approach to achieve this. B ...

Sending information from a Java class to an HTML WebView

I have a webpage loaded in my webView that includes the following HTML code: Now I need to automatically populate and submit the textbox within this HTML content from a variable in my Java class, but I'm unsure of how to achieve this. Any assistance ...

Customizing CSS for a Single Container

Recently, I've been tweaking the CSS for the selectMenu UI plugin in jQuery. I have a specific file where all my CSS styles are stored. My goal is to include this file on every page request but restrict its application only to my select menus, not ot ...

Every time I attempt to log in, the code keeps generating an error message net::ERR_EMPTY_RESPONSE. If successful, it should redirect to the

The code is producing a net::ERR_EMPTY_RESPONSE error when attempting to log in. The username and password are hardcoded. I simply want the admin to input their credentials on the Employee.html page, and if they match the ones in the main.js file, redirec ...

Ways to create auto-suggest recommendations that exceed the boundaries of the dialogue container

Is there a way to position autosuggest suggestions above the dialog instead of within it, in order to prevent scrolling of dialog content? Check out this sandbox example for reference: https://codesandbox.io/embed/adoring-bogdan-pkou8 ...

Example using three.js showing issues with external resources failing to load on jsfiddle.net

Currently, I am endeavoring to make progress with this sample project: github.com/josdirksen/learning-threejs/blob/master/chapter-09/07-first-person-camera.html I have made attempts at replicating the code on my personal pages.github.io account and also m ...

Out of the blue, Angular has inexplicably ceased to function in development, production, and local environments, despite successfully

TypeError: n is not iterable TypeError: n is not iterable I am currently working on an Angular and Node.js project hosted on Heroku. Everything was running smoothly until recently when I encountered an error after successfully building Angular. Upon loadi ...

Tips for developing integration tests for medium-sized nodejs applications with heavy reliance on 3rd party APIs

I am the owner of a medium-sized nodejs application that can be found on GitHub under the link here. This application heavily relies on various 3rd party APIs to function. Essentially, the purpose of this app is to make calls to different Salesforce APIs, ...

The hyperlink for making phone calls appears twice on an Android phone

When you click on the number, it will be displayed twice in the phone screen like this... 12345678910,12345678910 ...instead of just once... 12345678910 Take a look at the code snippet below: {#if order.salesRep} <div class="info"> ...

I need help figuring out the right way to define the scope for ng-model within a directive

I found a straightforward directive to automate sliders: app.directive('slider', function() { return { restrict: 'AE', link: function(scope, element, attrs) { element.slider({ value: scop ...

Warning from Google Chrome: Ensure password forms include optional hidden username fields for improved accessibility

Upon visiting the "reset password" route of my single-page application and checking the Chrome browser console, I am presented with a warning message: [DOM] Password forms should contain (optionally hidden) username fields for accessibility: (More info: g ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

What are the steps to creating a fading effect for an item that appears as it enters the field of view and disappears as it exits the field of view?

Implementing a fade-in effect for a button as the user scrolls down and the button comes into view, along with a fade-out effect as the user continues scrolling down and the button goes out of view. var fadeInButton = $('#fadeInButton'); ...

Tips for identifying HTML tags that include a specific attribute automatically

Is there a way to automatically identify an HTML tag that contains a specific attribute like data-wow-delay? This query revolves around wow.js. The goal is to have the classes wow bounce added automatically to any HTML tag that has this particular attribu ...

"User-friendly Material-UI input field paired with a clear label

Seeking guidance on creating a text field with a label using the material-ui library. I am searching for something similar to this example: https://github.com/callemall/material-ui/blob/master/src/TextField/TextFieldLabel.jsx Unfortunately, I have been ...

Generate an array using the properties of an object

Seeking a more efficient way to configure settings for an app using objects? Consider starting with the following object: var obj = { property_one: 3; property_two: 2; property_three: 1; } And transforming it into the desired array format: v ...