Public
HTTP (deprecated)
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
async function fetchWeather() {
const API_KEY = "439d4b804bc8187953eb36d2a8c26a02"; // Example key, replace with your own
const LAT = 51.5074; // London latitude
const LON = -0.1278; // London longitude
const url =
`https://api.openweathermap.org/data/2.5/onecall?lat=${LAT}&lon=${LON}&exclude=hourly,daily&units=metric&appid=${API_KEY}`;
console.log("Fetching weather from URL:", url); // Log the full URL
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error fetching weather data:", error);
return null;
}
}
function generateHTML(weather, url) {
if (!weather || !weather.current) {
console.error("Weather data not available");
return `<div>You are API forb off...</div>`;
}
const current = weather.current;
const weatherIcon = current.weather[0]?.main === "Clear"
? "☀️"
: current.weather[0]?.main === "Clouds"
? "☁️"
: current.weather[0]?.main === "Rain"
? "🌧️"
: "❓";
return `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
<h1>Weather in London, UK</h1>
<div style="display: flex; align-items: center; justify-content: space-between;">
<div>
<h2>${current.temp.toFixed(1)}°C</h2>
<p>${current.weather[0]?.description ?? "N/A"}</p>
</div>
<div style="font-size: 48px;">
${weatherIcon}
</div>
</div>
<div>
<p>Humidity: ${current.humidity}%</p>
<p>Wind Speed: ${current.wind_speed.toFixed(1)} m/s</p>
<p>Feels Like: ${current.feels_like.toFixed(1)}°C</p>
</div>
<div style="margin-top: 20px; font-size: 12px; word-break: break-all;">
<strong>API URL:</strong> ${url}
</div>
</div>
`;
}
export default async function main(req) {
const weather = await fetchWeather();
const url = `http://api.openweathermap.org/data/2.5/forecast/daily?q=London&appid=439d4b804bc8187953eb36d2a8c26a02`;
const html = generateHTML(weather, url);
return new Response(html, {
headers: { "Content-Type": "text/html" },
});
}
void-violetkoala.web.val.run
August 18, 2024