Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a dynamic list using Express, HTML?

I need to make my list dynamic by taking the data from the JSON file I created, I need to make sure that when I click on an item in the list it then takes me to a specific item based on the id. I tried this way but it doesn’t work, the list must be dynamic.

My API Express:

import express from "express";
import tours from "./tours_file/tours.json" assert { type: "json" };

const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
  res.sendFile(
    "C:\\Users\\MartinaPangallo\\OneDrive - NEW TECHNOLOGY DEVELOPMENT ITALIA SRL\\Desktop\\sitoWebFE\\homepage.html"
  );
});

//----prendo tutti i tour

app.get("/tours", (req, res) => {
  res.json(tours);
});

//----Seleziono per id il mio tour

app.get("/tours/:id", (req, res) => {
  const { id } = req.params;
  const tour = tours.find((tour) => tour.id == id);
  res.json(tour);
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

The HTML and script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!DOCTYPE html>
<html lang="en">
  <head>
    <style></style>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Homepage</title>
    <style>
      .active {
        color: gainsboro;
        font-weight: bold;
      }
      .inactive {
        color: grey;
        font-weight: 100;
      }
    </style>
  </head>

  <body>
    <h1>Homepage</h1>
    <p>scegli o aggiungi un tour</p>

    <div class="output"></div>
    <script>
      const output = document.querySelector(".output");
      const output1 = document.createElement("div");
      const url = "tours.json";
      const ul = document.createElement;
      output.append(output1);
      output.append(ul);

      window.addEventListener("DOMContentLoaded", () => {
        output.textContent = "ready";
        loadData();
      });

      function loadData() {
        fetch(url)
          .then((rep) => rep.json())
          .then((data) => {
            //   console.log(data);
            addToPage(data);
          });
      }

      function addToPage(arr) {
        arr.array.forEach((element) => {
          console.log(element);
          const li = document.createElement("li");
          li.textContent = el.name;
          if (el.status) {
            li.classList.add("active");
          } else {
            li.classList.add("inactive");
          }
          ul.append(li);
          li.addEventListener("click", (e) => {
            li.classList.toggle("active");
            li.classList.toggle("inactive");
          });
        });
      }
    </script>
  </body>
</html>

My JSON:

[
  {
    "id": "1",
    "name": "The Forest Hiker",
    "difficulty": "easy",
    "country": "Trentino",
    "description": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  },
  {
    "id": "2",
    "name": "The Alpinist",
    "difficulty": "hard",
    "country": "Svizzera",
    "description": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  },
  {
    "id": "3",
    "name": "A Bicycle Trip",
    "difficulty": "easy",
    "country": "Sicilia",
    "description": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  },
  {
    "id": "3",
    "name": "Horse Trip",
    "difficulty": "easy",
    "country": "Francia",
    "description": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut 
  }
]

I need help because I’m not sure where I’m wrong.

>Solution :

Here are a living example based on your code demo page url

there are these problems in your code, most of them are in your html-

  1. fetch(url) and your url equals to tours.json. this is wrong, because you defined a endpoint in your express named tours, you can’t ask the express for tours.json.

  2. const ul = document.createElement; should be const ul = document.createElement('ul'); you want use it to create a ul, not assign it to another variable

  3. arr.array.forEach((element) should be arr.forEach((el) , because arr will be the array,and element should be el, because you try to use el in the code below.

  4. there are other small problem, i guess you can compare mine with yours.


Hope it helps

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading