This is a simple HTML file, index.html
, in a new directory for static files named public
. This file will be served as your static page. It contains placeholder elements for displaying data.
<!-- public/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Weather and News Dashboard</title>
</head>
<body>
<h1>Weather and News Dashboard</h1>
<div id="weather"></div>
<div id="news"></div>
<script src="script.js"></script>
</body>
</html>
In your main server file, server.js
, set up Express to serve this static file.
// server.js
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Server is running on <http://localhost:3000>');
});
Next, add routes in your Express server to handle API requests. These routes will fetch data from external APIs and send it back to the client.
// server.js
// ... previous code ...
const fetch = require('node-fetch');
app.get('/weather', async (req, res) => {
const weatherData = await fetch('URL_TO_WEATHER_API').then(res => res.json());
res.json(weatherData); // <-- respond to http request with json data
});
app.get('/news', async (req, res) => {
const newsData = await fetch('URL_TO_NEWS_API').then(res => res.json());
res.json(newsData);
});
Replace 'URL_TO_WEATHER_API'
and 'URL_TO_NEWS_API'
with the actual API endpoints. You might need to include API keys as query parameters.
Create script.js
in your public
folder. This script will make requests to your server endpoints and update the webpage dynamically.
// public/script.js
function fetchWeather() {
fetch('/weather')
.then(response => response.json())
.then(data => {
document.getElementById('weather').innerHTML = 'Current Weather: ' + data.summary;
});
}
function fetchNews() {
fetch('/news')
.then(response => response.json())
.then(data => {
document.getElementById('news').innerHTML = 'Top News: ' + data.headline;
});
}
fetchWeather();
fetchNews();
server.js
) acts as an intermediary, fetching data from external APIs and serving it through your own endpoints.script.js
) makes requests to these endpoints and updates the static page with the received data.