본문 바로가기
개발/리액트

axios를 이용한 날씨 정보 조회

by ^..^v 2020. 5. 22.
728x90
반응형

axios 

웹 브라우저와 node.js에서 사용할 수 있는 프로미스 기반의 HTTP 클라이언트

 

https://github.com/axios/axios

 

axios/axios

Promise based HTTP client for the browser and node.js - axios/axios

github.com

 

axios를 사용하면 응답 문서를 자동으로 JSON 형식으로 변환해 주므로, 별도의 변환 과정 없이 바로 사용이 가능합니다. 

axios.get('http://someapi.com')
.then(response => console.log(response))
.catch(error => console.log(error));

 

HTTP 메소드별 메소드를 제공하며 요청 본문은 메소드의 파라미터로 전달이 가능합니다. 

axios.post('http://someapi.com', { requestParameterObject })
.then(respose => console.log(response))
.catch(error => console.log(error));

 

 

axios를 이용해서 날씨 정보를 가져와서 출력하는 예제를 구현해 보겠습니다. 

 

#1 날씨 정보를 제공하는 OpenWeatherMap 사이트에 회원 가입

https://home.openweathermap.org/

 

Members

Enter your email address and we will send you a link to reset your password.

home.openweathermap.org

회원 가입 시 입력한 이메일 주소로 발송된 확인 메일을 확인(Verify your email)해야만 가입이 완료됩니다.

 

 

#2 API Key 확인

 

API 호출 형식 (https://openweathermap.org/current 참조)

 

api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key}
api.openweathermap.org/data/2.5/weather?q={city name},{state code}&appid={your api key}
api.openweathermap.org/data/2.5/weather?q={city name},{state code},{country code}&appid={your api key}

 

#3 앱 생성

C:\react> npx create-react-app weatherapp

 

 

#4 앱 실행

C:\react\weatherapp> npm start

 

 

#5  axios 라이브러리 추가

C:\react\weatherapp> npm install axios

 

 

#6 날씨 컴포넌트(Weather.js) 생성

import React, { Component } from 'react';
import axios from 'axios';
import './App.css';

class Weather extends Component {
    // 상태 변수 정의
    constructor(props) {
        super(props);
        this.state = { temp: 0, desc: '', icon: '', loading: true }
    }
    // 컴포넌트 생성 후 날씨 정보 조회
    componentDidMount() {
        const cityName = 'Seoul';
        const apiKey = 'ea53b6f001e4d38c68b87795ddeea08f';
        const url = `http://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}`;

        // fetch() 함수를 이용
        // fetch(url)
        //     .then(response => response.json())
        //     .then(responseData => {
        //         this.setState({
        //             temp: responseData.main.temp,
        //             desc: responseData.weather[0].description,
        //             icon: responseData.weather[0].icon,
        //             loading: false
        //         });
        //     })
        //     .catch(error => console.log(error));

        // axios 라이브러리 이용
        axios.get(url)
            .then(responseData => {
                console.log(responseData);
                const data = responseData.data;
                this.setState({
                    temp: data.main.temp,
                    desc: data.weather[0].description,
                    icon: data.weather[0].icon,
                    loading: false
                });
            })
            .catch(error => console.log(error));

    }
    // 날씨 정보 출력
    render() {
        const imgSrc = `http://openweathermap.com/img/w/${this.state.icon}.png`;
        if (this.state.loading) {
            return <p>Loading</p>;
        } else {
            return (
                <div className="App">
                    <img src={imgSrc}/>
                    <p>{this.state.temp}C</p>
                    <p>{this.state.desc}</p>
                </div>
            );
        }
    }
}

export default Weather;

 

 

#7 App.js에 날씨 컴포넌트 추가

import React from 'react';
import './App.css';
import Weather from './Weather.js';

function App() {
  return (
    <div className="App">
      <Weather/>
    </div>
  );
}

export default App;

 

 

#8 브라우저로 결과 확인

728x90
반응형

댓글