본문 바로가기
개발/Javascript

바닐라자바스크립트로 허접한 날씨 앱 만들기

by 안뇽! 2021. 9. 8.
반응형

리액트로 만들려고 했는데, 

uncaught (in promise) syntaxerror: unexpected token < in json at position 0

에러의 비밀을 풀지 못하고 접었다.

 

아쉬워서 DOM으로나마 만들었다. 후

 

도시 이름은 API에 등록된 이름만 가능하다. NewYork이라 치면 안나오고 New York이라 쳐야 한다.

 

CSS는 귀찮아서 안했다.

 

 

 

https://github.com/ryu9663/weatherAlarm.git

 

GitHub - ryu9663/weatherAlarm: Yon can see the weather of city where you wonder

Yon can see the weather of city where you wonder. Contribute to ryu9663/weatherAlarm development by creating an account on GitHub.

github.com

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="globals.css">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form>
        <input id = 'city' type = 'textbox'/>
        <input type = 'submit' id = changeCity value = '클릭'/>
    </form>
    <div class = "de">
        <h5>기본값</h5>
    </div>

<script src='weather.js'></script>

</body>
</html>
const weatherLine = document.createElement('h4')
const temperatureLine = document.createElement('h4')
const cityLine = document.createElement('h4')

const de = document.querySelector('.de')

document.body.append(weatherLine)
document.body.append(temperatureLine)
document.body.append(cityLine)


let city = document.querySelector('#city')

let button = document.querySelector('#changeCity')

let count = 0
let cityName = 'Jecheon'

button.addEventListener('click',func)
function func(event){
    event.preventDefault()
    count++
    
    
    if(count === 0){ cityName = 'Jecheon'}
    else{cityName =  city.value}
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}`

fetch(url)
    .then(response => response.json())
    .then(data => {
        
        weatherLine.textContent = data.weather[0].main
        temperatureLine.textContent = `${(data.main.temp-273).toFixed(2)}도`
        cityLine.textContent = data.name
       
        
    })
}
// const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=479b71bd8170440dd418a65c5c00da87`

fetch(`https://api.openweathermap.org/data/2.5/weather?q=Jecheon&appid=${API_KEY}`)
    .then(response => response.json())
    .then(data => {
        
        weatherLine.textContent = data.weather[0].main
        temperatureLine.textContent = `${(data.main.temp-273).toFixed(2)}도`
        cityLine.textContent = data.name
       
        
    })
de.append(weatherLine)
de.append(temperatureLine)
de.append(cityLine)

 

반응형