본문 바로가기

IT/JavaScript

[Weather API] 날씨 정보 받아오기 / 401 에러

Weather API - OpenWeatherMap

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

현재 위치에 따른 날씨 정보를 얻어오기 위해 Weather API 를 이용했다.

 

방법부터 알아보자면

먼저 홈페이지에 접속해서 로그인, 또는 회원가입을 한다.

회원가입을 하고 나면 가입 시 입력한 mail 주소로 확인 메일이 오는데 'Verify your email' 을 눌러 승인을 해주면 된다.

 

다시 홈페이지로 와서

API 카테고리에 Current Weather Data - API doc 을 누른다.

 

 

여러 가지 중에 위도, 경도 를 통해 현재위치의 날씨를 가져올 수 있는 API 를 사용할 예정이다.

아래 API URL 을 인터넷 주소창 URL 에 입력한다.

 

 

{lat} 부분에 latitude(위도) 를 넣고

{lon} 부분에 longitude(경도) 를 넣는다.

 

<latitude, longitude 를 가져오는 방법>

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    console.log("You are in ", lat, lon);
}
function onGeoError(){
    alert("Can't find you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

 

console.log 에 찍힌 위도 와 경도 를 복사해서

 

https://api.openweathermap.org/data/2.5/weather?lat=37.23&lon=127.06&appid={API key}

 

이렇게 넣는다. {} 는 제외

이제 마지막 API key 를 입력해야 하는데

 

홈페이지 우측 위에 본인의 닉네임을 클릭하고 My API keys 를 누르면 API key 를 확인할 수 있다.

 

 

key 를 복사해서 {API key} 자리에 넣는다.

 

https://api.openweathermap.org/data/2.5/weather?lat=37.23&lon=127.06&appid=1234

 

{lat}, {lon}, {API key} 까지 입력하고 URL 에 검색해주면 좌표를 받을 수 있다.

 

 

그런데!?

 

401 에러가 떴다.

 

<401 Error>

 

API key 가 유효하지 않다고 한다.

방금 받은건데... 몇번이고 확인했지만 key 가 잘못된 건 아니었다.

위에 친절히 알려주고 있는 에러 안내 페이지로 이동하여 살펴보았다.

 

https://openweathermap.org/faq#error401 for more info.

 

 

친절하네...

무엇보다 API key 가 활성화 되지 않았고 몇 시간 내에 활성화 되어 사용할 수 있다 는게 눈에 띈다..

 

그래도 혹시몰라 검색해보니

처음 API key 를 발급받으면 바로 사용하지는 못하고 일정시간이 지나야 사용할 수 있다고 한다. 보통 1시간 이내로?

그래서 기다렸더니 됐다.

 

이런식으로 좌표 날씨 정보를 받을 수 있다.

 

{
"coord":{"lon":127,"lat":37},
"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10n"}],
"base":"stations",
"main":{"temp":297.51,"feels_like":298.53,"temp_min":295.63,"temp_max":297.97,"pressure":996,"humidity":97},
"visibility":10000,
"wind":{"speed":5.14,"deg":170},
"rain":{"1h":0.62},
"clouds":{"all":100},
"dt":1688480252,
"sys":{"type":1,"id":809,"country":"KR","sunrise":1688415361,"sunset":1688468140},
"timezone":32400,
"id":657,
"name":"-dong",
"cod":200
}

 

URL 을 확인했으니 이제 다음 코드를 실행시켜보자.

 

const API_KEY = "eed33bc1ba";

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`;
    console.log(url);
}
function onGeoError(){
    alert("Can't find you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

 

위의 코드와 같이 문자열 사이에 변수를 넣을 때에는 "", '' 이 아닌 백틱(``) 을 사용해야 하며

변수는 ${} 로 불러온다.

 

console.log() 로 url 을 출력하고 url 을 클릭해보면 아까와 같은 날씨 정보를 확인해볼 수 있다.

 

이런식으로 차근차근 코드를 확인하면서 진행하면 코드의 에러를 제 때 확인하며 진행할 수 있다.

 

<최종 코드>

const API_KEY = "eed33bc1ba";

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
    fetch(url)
    .then((response => response.json()))
    .then((data) => {
        console.log(data);
        const weather = document.querySelector("#weather span:first-child");
        const city = document.querySelector("#weather span:last-child");
        city.innerText = data.name;
        weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
    });
}
function onGeoError(){
    alert("Can't find you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

 

html 은 아래와 같다.

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <title>Weather</title>
</head>

<body>
    <div id="weather">
        <span></span>
        <span></span>
    </div>
    <script src="js/weather.js"></script>
</body>

</html>

 

마지막 javascript 코드에서 몇 가지 추가 된 부분은

다음 글에서 정리하겠다.

 

'IT > JavaScript' 카테고리의 다른 글

[JavsScript] function 호출하기  (0) 2023.06.17