skip to Main Content

While I fetched the data successfully, I cannot manage to display the data to an HTML efficiently.

The only way that that it works(how far I’ve gotten) is with two endpoints. Where one endpoint is to load the API data and the other endpoint is to load the HTML with a script.

(With the two endpoints I get a the data loaded to the HTML, but first have to load the first then the second which I find to not be the best solution)

Endpoints:

//rest of the code

app.get("/", async(req, res) => {

    const weatherData = await fetchData();
    
    res.send(weatherData);
    
});

app.get("/test", (req,res) =>{

    res.sendFile(__dirname + "/public/home.html");
});

//rest of the code

Script:


fetch("/")
.then(response => response.json())
.then(weatherData => {
    
    document.getElementById("test").innerHTML = weatherData.resolvedAddress;

    document.getElementById("test1").innerHTML = weatherData.description;

    document.getElementById("test2").innerHTML = weatherData.days[0].temp;

    document.getElementById("test3").innerHTML = weatherData.days[0].tempmax;

    document.getElementById("test4").innerHTML = weatherData.days[0].tempmin;

    document.getElementById("test5").innerHTML = weatherData.days[0].description;

})
.catch(error => console.log(error));

The question I have: Is there a way to combine the two endpoints(that the data loads to the html)?

2

Answers


  1. you can use a html template engine to fill your data more easily. like EJS or pug.

    for ejs:

    const express = require('express');
    const app = express();
    
    app.set('view engine', 'ejs');
    
    app.get('/', (req, res) => {
        const data = { title: "EJS Example", user: { name: "John" }, items: ["item1", "item2"] };
        res.render('index', data);
    });
    
    app.listen(3000);
    

    views/index.ejs:

    <h1>Hello, <%= user.name %>!</h1>
    <ul>
      <% items.forEach(item => { %>
        <li><%= item %></li>
      <% }); %>
    </ul>
    
    Login or Signup to reply.
  2. The question I have: Is there a way to combine the two endpoints(that the data loads to the html)?

    For a more seamless experience, you should consider using a templating engine like EJS or a similar library, as Arnashia suggested.

    Is there any way to do this without installing any dependencies

    The method you’re currently using is indeed the correct approach if you want to achieve this without installing any dependencies.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search