-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
65 lines (56 loc) · 2.01 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const express = require('express');
const http = require('http');
require('dotenv/config')
const app = express();
const port = process.env.PORT || 3000;
const apiKey = process.env.API_KEY
// Serve the static assets (CSS, JS, images) from the "public" folder
app.use(express.static(__dirname + '/public'));
// Serve the HTML page when a GET request is made to the root URL
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Set up the weather API endpoint
app.get('/weather/:city', async (req, res) => {
const city = req.params.city;
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
http.get(url, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
try {
const weatherData = JSON.parse(data);
const city = `${weatherData.name}, ${weatherData.sys.country}`;
const date = new Date(weatherData.dt * 1000).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
const condition = weatherData.weather[0].description;
const icon = weatherData.weather[0].icon;
const temperature = `${Math.round(weatherData.main.temp)} °C`;
const rainfall = `${weatherData.rain ? weatherData.rain['1h'] || weatherData.rain['3h'] || 0 : 0} mm`;
const windSpeed = `${weatherData.wind.speed} m/s`;
const humidity = `${weatherData.main.humidity} %`;
const weather = {
city,
date,
condition,
icon,
temperature,
rainfall,
windSpeed,
humidity
};
res.json(weather);
} catch (error) {
res.status(500).send('Error retrieving weather data');
}
});
}).on('error', (error) => {
res.status(500).send('Error retrieving weather data');
});
});
app.listen(port, () => console.log(`Server Running On PORT ${port}: http://localhost:${port}`));