날씨 api 백엔드로 수정

This commit is contained in:
dyhj625 2025-04-01 14:45:21 +09:00
parent f975273c47
commit e5acfa5cf3

View File

@ -269,6 +269,7 @@
import { useRouter } from 'vue-router';
import { useThemeStore } from '@s/darkmode';
import { computed, onMounted, ref, watch } from 'vue';
import axios from '@api';
const baseUrl = import.meta.env.VITE_SERVER;
@ -353,41 +354,42 @@
const weatherKorean = computed(() => weather.value.description || '날씨 정보 없음');
onMounted(() => {
navigator.geolocation.getCurrentPosition(async (position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const apiKey = '3505b3500aacf34c4497bf449996ea09';
const url = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=kr`;
navigator.geolocation.getCurrentPosition(async (position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
try {
const res = await fetch(url);
const data = await res.json();
try {
const res = await axios.get(`/weather`, {
params: { lat, lon },
withCredentials: true,
});
const now = new Date();
const raw = res.data;
const data = JSON.parse(raw.data);
//
const closest = data.list.reduce((prev, curr) => {
const prevTime = new Date(prev.dt_txt).getTime();
const currTime = new Date(curr.dt_txt).getTime();
const nowTime = now.getTime();
if (!data || !Array.isArray(data.list) || data.list.length === 0) {
console.error('날씨 데이터 형식 오류 또는 없음:', data);
return;
}
const prevDiff = Math.abs(prevTime - nowTime);
const currDiff = Math.abs(currTime - nowTime);
const now = new Date();
const closest = data.list.reduce((prev, curr) => {
const prevTime = new Date(prev.dt_txt).getTime();
const currTime = new Date(curr.dt_txt).getTime();
const nowTime = now.getTime();
const prevDiff = Math.abs(prevTime - nowTime);
const currDiff = Math.abs(currTime - nowTime);
return prevDiff < currDiff ? prev : curr;
});
if (prevDiff < currDiff) return prev;
if (prevDiff > currDiff) return curr;
return prevTime < currTime ? prev : curr;
weather.value.icon = closest.weather[0].icon.replace(/n$/, 'd');
weather.value.description = closest.weather[0].description;
weather.value.tempMin = Math.round(closest.main.temp_min);
weather.value.tempMax = Math.round(closest.main.temp_max);
} catch (e) {
console.error('날씨 정보 가져오기 실패:', e);
}
});
weather.value.icon = closest.weather[0].icon.replace(/n$/, 'd');
weather.value.description = closest.weather[0].description;
weather.value.tempMin = Math.round(closest.main.temp_min);
weather.value.tempMax = Math.round(closest.main.temp_max);
} catch (e) {
console.error('날씨 정보 가져오기 실패:', e);
}
});
});
const handleLogout = async () => {