cuaca / server.js
citedd's picture
Initial commit: Weather Dashboard with liquid glass
9b18a76 verified
Raw History Blame Contribute Delete
2.04 kB
const express = require('express');
const path = require('path');
const https = require('https');
const app = express();
const PORT = process.env.PORT || 7860;
app.use(express.static(path.join(__dirname, 'public')));
// Geocoding + weather proxy using OpenMeteo (free, no API key)
app.get('/api/weather', (req, res) => {
const { lat, lon, name } = req.query;
if (!lat || !lon) {
return res.status(400).json({ error: 'lat and lon required' });
}
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&current=temperature_2m,relative_humidity_2m,apparent_temperature,weather_code,wind_speed_10m,pressure_msl,uv_index&daily=weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset&temperature_unit=celsius&wind_speed_unit=kmh&timezone=auto&forecast_days=6`;
console.log('Fetching weather:', url);
https.get(url, (apiRes) => {
let data = '';
apiRes.on('data', c => data += c);
apiRes.on('end', () => {
try {
const parsed = JSON.parse(data);
parsed.location_name = name || '';
res.json(parsed);
} catch(e) {
res.status(500).json({ error: 'Failed to parse weather data' });
}
});
}).on('error', (e) => {
res.status(500).json({ error: 'Weather API error', message: e.message });
});
});
app.get('/api/search', (req, res) => {
const { q } = req.query;
if (!q) return res.status(400).json({ error: 'query required' });
const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(q)}&count=5&language=en&format=json`;
https.get(url, (apiRes) => {
let data = '';
apiRes.on('data', c => data += c);
apiRes.on('end', () => {
try {
const parsed = JSON.parse(data);
res.json(parsed);
} catch(e) {
res.status(500).json({ error: 'Search failed' });
}
});
}).on('error', (e) => {
res.status(500).json({ error: e.message });
});
});
app.listen(PORT, () => {
console.log(`Weather Dashboard running on port ${PORT}`);
});