Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
75 lines (62 loc) · 2.15 KB
/
Copy pathserver.js
File metadata and controls
75 lines (62 loc) · 2.15 KB
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
66
67
68
69
70
71
72
73
74
75
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// API Configuration - kept secure on server
const API_KEY = process.env.API_KEY;
const BASE_URL = 'https://api.openweathermap.org/data/2.5/weather';
// Middleware
app.use(cors());
app.use(express.json());
// Weather API endpoint - MUST be defined before static middleware
app.get('/api/weather', async (req, res) => {
const { city } = req.query;
if (!city) {
return res.status(400).json({ error: 'City parameter is required' });
}
try {
const response = await axios.get(BASE_URL, {
params: {
q: city,
appid: API_KEY,
units: 'metric'
}
});
const data = response.data;
// Transform data for frontend
const weatherData = {
city: data.name,
temp: data.main.temp,
condition: data.weather[0].description,
icon: data.weather[0].icon,
humidity: data.main.humidity,
wind: data.wind.speed
};
res.json(weatherData);
} catch (error) {
if (error.response) {
// Handle OpenWeatherMap API errors
if (error.response.status === 404) {
return res.status(404).json({ error: 'City not found. Please check the city name.' });
}
if (error.response.status === 401) {
return res.status(500).json({ error: 'Invalid API key' });
}
}
console.error('Weather API Error:', error.message);
res.status(500).json({ error: 'Failed to fetch weather data. Please try again.' });
}
});
// Serve static files (html, css, js, video)
app.use(express.static(path.join(__dirname)));
// Fallback: serve index.html for root route
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Start server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
console.log('Open in browser: http://localhost:' + PORT);
});