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>