[React] Axios

장윤희·2023년 3월 4일
0

React

목록 보기
3/3
post-thumbnail

서버와 데이터를 주고받기 위해서는 HTTP 통신을 해야 하는데,
React에는 HTTP Client(HTTP 상에서 커뮤니케이션을 하는 자바 기반 컴포넌트) 내장 클래스가 존재하지 않는다.
따라서 React에서 AJAX(Asynchronous Javascript And XML)를 구현하려면 JavaScript 내장객체인 XMLRequest를 사용하거나, 다른 HTTP Client를 사용해야 한다.

Axios이란?

Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리

특징

  • CSRF 보호 기능이 내장
  • Promise(ES6) API 사용
  • 요청과 응답 데이터의 변형
  • HTTP 요청 취소 및 요청과 응답을 JSON 형태로 자동 변경

npm설치, import

npm install axios

//자신이 진행중인 프로젝트 상위에 import 시켜주기
import axios from 'axios'

사용법

기본 Params (Method, Url, Data (optional), Params (optional))

axios({
    method: "get",
    url: "url",
    responseType: "type"
}).then(function (response) {
    // response Action
});

REST API

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

HTTP Methods

GET (데이터 조회)

GET메서드는 데이터를 조회하는 것으로 값이나 상태등을 바꿀 수 없다.
json으로 데이터를 주고받아야 하기 때문에 response도 json형태이다.
axios.get(url,[,config])

//get 메서드
axios.get("url")
    .then((response) => {
        console.log(response.data);	//정상 통신 후 응답된 메시지 출력
    })
    .catch((error)=>{
        console.log(error);	//오류발생시 실행
	}).then(function() {
        // 항상 실행
    });
    
// async await 함수를 사용할 때, 
try {
	const data = await axios.get("url");
} catch {
	// 오류 발생시 실행
}

POST (데이터 등록)

새로운 리소스를 생성(create)할 때 사용한다.
POST 메서드의 두 번째 인자는 본문으로 보낼 데이터를 설정한 객체 리터럴을 전달한다.
주소창에 쿼리스트링이 남지 않는다
axios.post(url, data[, config])

//post 메서드
axios.post("url",{
    	name:"info",
        num:"0"
    })
    .then((response) => {
        console.log(response.data); //정상 통신 후 응답된 메시지 출력
    })
    .catch((error)=>{
        console.log(error); //오류발생시 실행
	}).then(function() {
        // 항상 실행
    });
    
// async await 함수를 사용할 때, 
try {
	const data = await axios.post("url");
} catch {
	// 오류 발생시 실행
}

PUT (데이터 수정)

axios.put(url, data[, config])
REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 갱신하는 목적으로 사용된다.
get -> post 과정을 거치기 때문에 post 메서드와 비슷한 형태이다.

DELETE (데이터 제거)

axios.delete(url[, config])
REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 삭제하는 목적으로 사용한다.
일반적으로 delete 메서드에는 body가 비어있지만, query나 params가 많아져 header에 많은 정보를 담을 수 없는 경우에는 두번째 인자에 data를 추가해 줄 수 있다.
Delete메서드는 HTML Form 태그에서 기본적으로 지원하는 HTTP 메서드가 아니다.

일반적인 경우

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 {
	// 오류 발생시 실행
}

많은 데이터를 요청할 경우

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
  });

AJAX (Asynchronous Javascript And XML)

서버와 통신하기 위해 XMLHttpRequest 객체를 이용해서 전체 페이지를 새로 고치지 않고도 페이지의 일부만을 위한 데이터를 로드하는 기법이다.
JSON, XML, HTML 그리고 일반 텍스트 형식 등을 포함한 다양한 포맷을 비동기방식으로 주고받을 수 있다.
정리하자면, 자바스크립트를 통해서 서버에 데이터를 요청하는 것이다.

Axios VS Fetch API

  • Fetch()body 프로퍼티를 사용하고,axiosdata 프로퍼티를 사용한다.
  • Fetch에서 body부분은 stringify()로 되어있고 axios는 객체로 넘긴다.
  • Fetch의 url이 Fetch()함수의 인자로 들어가고, axios에서는 url이 option객체로 들어간다.

Fetch API

//fetch
const url ='http://localhost3000/test`
const option ={
   method:'POST',
   header:{
     'Accept':'application/json',
     'Content-Type':'application/json';charset=UTP-8'
  },
  body:JSON.stringify({
  	name:'sewon',
    	age:20
  })

  fetch(url,options)
  	.then(response => console.log(response))

axios

//axios
const option ={
  url ='http://localhost3000/test`
   method:'POST',
   header:{
     'Accept':'application/json',
     'Content-Type':'application/json';charset=UTP-8'
  },
  data:{
  	name:'sewon',
    	age:20
  }

  axios(options)
  	.then(response => console.log(response))

참고자료
https://velog.io/@shin6403/React-axios%EB%9E%80-feat.-Fetch-API
https://wonit.tistory.com/305

profile
멋쟁이

0개의 댓글