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
you can use a html template engine to fill your data more easily. like
EJS
orpug
.for ejs:
views/index.ejs
:For a more seamless experience, you should consider using a templating engine like EJS or a similar library, as Arnashia suggested.
The method you’re currently using is indeed the correct approach if you want to achieve this without installing any dependencies.