Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
69 lines (57 loc) · 1.81 KB
/
Copy pathserver.js
File metadata and controls
69 lines (57 loc) · 1.81 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
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Serve static files from the current directory
app.use(express.static(path.join(__dirname)));
// Route for the main page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// API endpoint for weather data (proxy to OpenWeather API)
app.get('/api/weather', async (req, res) => {
const city = req.query.q;
const apiKey = process.env.OPENWEATHER_API_KEY;
if (!apiKey) {
return res.status(500).json({
error: 'API key not configured. Please set OPENWEATHER_API_KEY environment variable.'
});
}
if (!city) {
return res.status(400).json({ error: 'City parameter is required' });
}
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
);
if (!response.ok) {
throw new Error(`Weather API responded with status: ${response.status}`);
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Error fetching weather data:', error);
res.status(500).json({ error: 'Failed to fetch weather data' });
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
app.listen(PORT, () => {
console.log(`Weather App server running on http://localhost:${PORT}`);
console.log(`Health check available at http://localhost:${PORT}/health`);
});