Group Study (2021-2022)/React

[React] 6주차 스터디 - react-axios

알 수 없는 사용자 2021. 11. 16. 18:08



0. AJAX

Axios에 대한 이해를 하기 위해서는 먼저 AJAX에 대한 이해가 우선되어야 한다. AJAX Asynchronous Javascript And Xml의 약자로, Javascript의 라이브러리의 하나이다. 브라우저가 가지고 있는 XMLHttpRequest 객체를 이용하여, 페이지 일부만을 위한 데이터를 로드하는 기법으로 Javascript를 사용한 비동기 통신, 서버와 클라이언트 간에 XML 데이터를 주고받는 기술이다.


1. Axios 개요

리액트에서 AJAX를 구현하려면, Javascript의 내장객체인 XMLRequest를 사용하거나, HTTP Client를 사용해야 한다. Axios는 리액트에서 많이 쓰이는 HTTPClient 라이브러리의 하나이다. Axios는 Promise 기반이고, async/await 코드를 쉽게 구현할 수 있게 해준다.

 


2. Axios 특징 및 장점

  • 오래된 브라우저에서도 지원한다.
  • 요청을 중단할 수 있다.
  • response timeout을 쉽게 지정할 수 있다.
  • CSRF 보호 기능이 내장되어 있다.
  • Promise(ES6) API를 사용한다.
  • HTTP 요청 취소 혹은 요청과 응답을 JSON 형태로 자동 변경해준다.

3. Axios 사용법

0. REST API

REST란, 어떤 자원에 대해 CRUD(Create, Read, Update, Delete) 연산을 수행하기 위해 URI로 요청을 보내는 것으로 Get, Post 방식의 method를 사용하여 요청을 보내며, 요청을 위한 자원은 특정한 형태(ex. JSON)로 표현된다. 이러한 REST 기반의 API를 웹으로 구현한것이 REST API이다. 

 

REST API에는 대표적으로 4가지의 HTTP 메서드를 행위의 수단으로 사용한다.

1. GET : 데이터 조회
2. POST : 데이터 등록 및 전송
3. PUT: 데이터 수정
4. DELETE: 데이터 삭제

1. Axios 다운로드

각자 환경에 맞는 방법에 따라 Axios를 설치하면 되는데, 대표적으로 npm이나 yarn을 사용하기 때문에 npm, yarn 환경에서 Axios를 설치하는 코드를 정리해보면 다음과 같다.

  • npm 환경에서 Axios 설치

    npm install axios​


  • yarn 환경에서 Axios 설치

    yarn add axios

2. Axios 사용하기

Axios 통신에서 가장 많이 사용되는 HTTP Methods 4가지(Get, Post, Put, Delete) 에 대해 정리해보려고 한다.

 

  • GET ; 입력한 url에 존재하는 자원에 요청을 할 때 사용한다.
    코드의 표현 : axios.get(url[, config])

    get 메서드를 사용하는 상황은 크게 2가지 경우가 있다.
    1. 단순 데이터(페이지 요청, 지정된 요청) 요청을 수행하는 경우
    2. 파라미터 데이터를 포함하는 경우 (ex. 사용자 번호에 따른 조회)

    1. 단순 데이터 요청을 수행하는 경우
    // callback 을 사용할 때,
    axios.get("url")
        .then(function (response) {
             // response  
        }).catch(function (error) {
            // 오류발생시 실행
        }).then(function() {
            // 항상 실행
        });
        
    // async await 함수를 사용할 때, 
    
    try {
    	const data = await axios.get("url");
    } catch {
    	// 오류 발생시 실행
    }​

    2. 파라미터 데이터를 포함하는 경우
    axios.get("url", {
          params: {
            id: 123
          }
        })
        .then(function (response) {
             // response  
        }).catch(function (error) {
            // 오류발생시 실행
        }).then(function() {
            // 항상 실행
        });
       
       
    // async await 함수를 사용할 때, 
    
    try {
    	const data = await axios.get("url", params: { id: 123 });
    } catch {
    	// 오류 발생시 실행
    }​

    ※ get을 사용하는 1번, 2번 상황에 따라 params: {}의 객체가 있는지 없는지 결정됨을 알 수 있다.


  • POST ; 새로운 리소스를 생성할 때 사용한다.
    코드의 표현 : axios.post(url, data[, config])

    post 메서드는 일반적으로 데이터를 Message Body에 포함시켜 보내며, get 메서드에서 params를 사용한 경우와 비슷하게 수행된다.

    axios.post("url", {
            username: "",
            password: ""
        })
        .then(function (response) {
             // response  
        }).catch(function (error) {
            // 오류발생시 실행
        }).then(function() {
            // 항상 실행
        });
        
    // async await 함수를 사용할 때, 
    
    try {
    	const data = await axios.post("url");
    } catch {
    	// 오류 발생시 실행
    }


  • PUT ; REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 갱신하는 목적으로 사용한다.
    코드의 표현 : axios.put(url, data[, config])

    PUT 메서드는 서버 내부적으로 GET -> POST 의 과정을 거치기 때문에 POST 메서드와 비슷한 형태이다.

    axios.put("url", {
            username: "",
            password: ""
        })
        .then(function (response) {
             // response  
        }).catch(function (error) {
            // 오류발생시 실행
        }).then(function() {
            // 항상 실행
        });
        
    // async await 함수를 사용할 때, 
    
    try {
    	const data = await axios.put("url", { username: "", password: ""});
    } catch {
    	// 오류 발생시 실행
    }
     
  • DELETE ; REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 삭제하는 목적으로 사용한다.
    코드의 표현 : axios.delete(url, data[, config])

    delete 메서드는 형태는 get과 비슷하지만, 한번 delete 메서드가 서버에 들어가게 되면, 서버 내에서 삭제 process를 진행하게 된다. 일반적으로 delete 메서드에는 body가 비어있지만, query나 params가 많아져 header에 많은 정보를 담을 수 없는 경우에는 두번째 인자에 data를 추가해 줄 수 있다.

    1. 일반적인 delete

    axios.delete('/user?ID=12345')
      .then(function (response) {
        // handle success
        console.log(response);
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
      
      // async await 함수를 사용할 때, 
    
    try {
    	const data = await axios.delete("url");
    } catch {
    	// 오류 발생시 실행
    }​


    2. 많은 데이터를 요청할 경우

    axios.delete('/user?ID=12345',{
        data: {
          post_id: 1,
          comment_id: 13,
          username: "foo"
        }
      })
      .then(function (response) {
        // handle success
        console.log(response);
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });​



 

4. React에서 Axios 실습

1. server의 axios를 이용하여 get 요청 받아온 데이터를 화면에 표시해보기

 

#src/components/PostList.js

import React, { Component } from "react"
import axios from 'axios'

class PostList extends Component{
    constructor(props){
        super(props)

        this.state={
            posts:[],
            post1:[]
        }
    }

    componentDidMount(){
        axios.get('header 정보 있는 서버 주소')//header get 요청
        .then(response => {
            console.log(response)
            this.setState({posts: response.data})
        })
        .catch(error => {
            console.log(error)
        }) 
        axios.get('slide 정보 있는 서버 주소') //slide get 요청
        .then(response => {
            console.log(response)
            this.setState({post1: response.data})
        })
        .catch(error => {
            console.log(error)
        })
    }

    render(){
        const {posts}=this.state
        const {post1}=this.state
        return(
            <div>
                List of Header
                {
                    posts.length ?
                    posts.map(post => <div key={post.id}>{post.header}</div>):
                    null
                }
                List of Slide
                {
                    post1.length ?
                    post1.map(post => <div key={post.id}>{post.slide}</div>):
                    null
                }
        </div>
        )
    }
}

export default PostList
#src/App.js

import React, { Component } from "react";
import logo from './logo.svg';
import './App.css';
import PostList from "./components/PostList";

class App extends Component {
  render() {
    return(
      <div className="App">
        <PostList/>
      </div>
    )
  }
}

export default App

실행결과)

2. 로그인 Form의 정보를 post 방식으로 서버의 데이터베이스에 저장하기

#src/components/PostForm.js

import React, { Component } from "react"
import axios from 'axios'

class PostForm extends Component{
    constructor(props){
        super(props)

        this.state={
            userId:'',
            userPassword: ''
        }
    }

    changeHandler = (e) => {
        this.setState({[e.target.name]:e.target.value})
    }

    submitHandler = (e) => {
        e.preventDefault()
        console.log(this.state)
        axios({method:'post', url:'posturl 주소',data:this.state});
    }
    render(){
        const {userId,userPassword}=this.state
        return(
        <div>
            <form onSubmit={this.submitHandler}>
                <div>
                    <input type="text" name="userId" value={userId} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="userPassword" value={userPassword} onChange={this.changeHandler}/>
                </div>
                <button type="submit">Submit</button>
            </form>
        </div>
        )
    }
}

export default PostForm
#src/App.js

import React, { Component } from "react";
import logo from './logo.svg';
import './App.css';
import PostList from "./components/PostList";
import PostForm from "./components/PostForm";

class App extends Component {
  render() {
    return(
      <div className="App">
        <PostForm/>
        {/* <PostList/> */}
      </div>
    )
  }
}

export default App

 


번외) 

 

React의 부트 스트랩과 Axios을 적절히 응용해 사용하면, 다채로운 웹페이지를 꾸밀 수 있습니다!
다음은 bootstrap을 통한 웹페이지에 Axios 기능을 섞어 만든 실행 결과의 예시 사진입니다.

 


Axios에 대한 더 자세한 내용은 다음의 링크에서 확인할 수 있습니다.

https://github.com/axios/axios