본문 바로가기
FRONT-END/REACT

[REACT] Axios

by 썬키 2023. 3. 10.
Axios

 

Axios는 React에서 자주 사용되는 HTTP 클라이언트 라이브러리 중 하나이다.

(* HTTP 클라이언트 라이브러리 : 서버로부터 데이터를 가져오는데에 사용)

Axios를 이용해 서버에 데이터를 요청하고 받을 수도 있고, 서버에 데이터를 보낼 수도 있다.

 

Axios의 장점

 

Axios는 비동기 HTTP 통신을 수행하는 라이브러리 중 하나이다.

비동기 통신은 요청을 보내고 서버로부터 응답을 받을 때, 프로그램의 실행 흐름을 차단하지 않고,

다른 작업을 수행할 수 있도록 한다. 이를 통해 웹 애플리케이션의 성능을 향상시킬 수 있다.

 

기본 문법

 

// GET 요청을 보냅니다.
axios.get(url[, config])
// POST 요청을 보냅니다.
axios.post(url[, data[, config]])
// PUT 요청을 보냅니다.
axios.put(url[, data[, config]])
// DELETE 요청을 보냅니다.
axios.delete(url[, config])

axios.get('https://api.example.com/users')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 

jQuery의 ajax와 사용법이 거의 흡사하다고 할 수 있다.

 

통신 성공시에는 .then함수를 실행, 실패시에는 .catch 함수를 실행하는데

이 때, 두 함수는 모두 생략이 가능하다.

 

 

사용법 1 - 서버에서 데이터 받아오기

 

서버단에 다음과 같은 메서드가 있다고 가정하자.

 

@ResponseBody
@GetMapping("/human")
public HumanDTO getDto() {
	HumanDTO human = new HumanDTO(1001, "홍길동", "서울시");
	return human;
}

 

사용자가 '/human' URL을 요청하면 human 객체를 리턴하는 메서드이다.

 

import React, {useEffect}  from 'react';
import axios from 'axios';

export default function App() {
	
    // 컴포넌트가 처음 마운트 됐을 때만 실행되게 하기 위한 useEffect 함수 사용
    useEffect( ()=>{
    	const fetchData = async () => {
        	const response = await axios.get('http://localhost:3000/human', {})
            .then(function(response) {
            	console.log(response.data);
            })
            .catch(function(error) {
            	console.log(error)
            })
        }
        
        fetchData();
        
    }, [])
    
}

 

console에서 확인해본 서버에서 받아온 데이터

 

서버에서 넘겨준 데이터를 클라이언트 콘솔창에서 잘 확인할 수 있다.

 

 

사용법 2 - 서버에 데이터 전달하고 데이터 받기

 

public class HumanDTO {
	private int number;
	private String name;
	private String address;
}

 

세 가지의 필드를 가진 HumanDTO가 있다고 가정하자.

 

@ResponseBody
@GetMapping("/param_obj")
public String param_object(HumanDTO human) {
    System.out.println("human: " + human.toString());
    return "OK";
}

 

클라이언트 쪽에서 받은 human 객체를 콘솔에 출력하고, 클라이언트에는 "OK"를 리턴하는 메서드이다.

 

import React, {useEffect}  from 'react';
import axios from 'axios';

export default function App() {

  useEffect( () => {

    const fetchData = async () =>  {
      const response = await axios.get('http://localhost:3000/param_obj',{ params :{"number":1, "name":"홍길동", "address":"경기도"} });
      console.log(response);
    }

    fetchData();

  }, [])

  return (
    <div>

    </div>
  )

}

 

axios 라이브러리를 이용하여 서버에 데이터를 전달해보았다.

 

서버측 콘솔창에서 확인할 수 있는 넘어온 데이터

 

클라이언트 콘솔창에서 확인할 수 있는 서버에서 넘겨준 데이터

 

서버와 클라이언트간의 데이터 송/수신이 성공적으로 이루어진 것을 확인할 수 있다.

'FRONT-END > REACT' 카테고리의 다른 글

[REACT] preventDefault()  (0) 2023.03.10
[REACT] form 데이터를 비동기로 서버에 전달  (0) 2023.03.10
[REACT] 쿠키와 세션에 값 저장하기  (0) 2023.03.09
[REACT] Hooks(2) - useEffect  (0) 2023.03.09
[REACT] Hooks(1) - useState  (0) 2023.03.08

댓글