AXIOS란? (feat. Fetch API)

두선아 Dusuna·2022년 8월 14일
5

AXIOS는 Promise API를 활용하는 HTTP 비동기 통신 라이브러리입니다.

Referance:
https://axios-http.com/kr/docs/api_intro
https://www.codegrepper.com/code-examples/javascript/axios+try+catch
https://koras02.tistory.com/48
https://yamoo9.github.io/axios/guide/api.html


AXIOS를 알아보기 전에,
먼저 AJAX, Fetch API를 간단히 정리해보았습니다.

AJAX는?

  • Asynchronous(비동기) Javascript And Xml
  • JavaScript 라이브러리 중 하나
    • 자바스크립트를 통해서 서버에 request, response
    • JavaScript를 사용하여 클라이언트, 서버 간통신, 즉 비동기적으로 XML 데이터를 주고 받습니다.
    • ex) 동기식과 비동기식 방식의 차이

Fetch API는?

  • 일반적으로 API를 연동하기 위해 사용하던 방식입니다.
  • 자바스크립트 bulit-in 라이브러리

Fetch API vs AXIOS

같은 코드로 비교하는 Fetch와 AXIOS

Fetch API

  • body안에 정보
  • url은 ()안에 인자로
  • body는 stringify()
const url = '요청할 주소'
const options = {
  method: 'POST',
  header: {
     'Accept' : 'application/json',
     'Content-Type':'application/json';charset=UTP-8'
  },
  body:JSON.stringify({
     name: 'test'
  })
  
  fetch(url.options)
     .then(response => console.log(response))
}

AXIOS

  • data안에 정보
  • url은 option 객체 안에 값으로
const option = {
   url = '요청할 주소'
   method:'POST',
   header: {
     'Accept':'application/json',
     'Content-Type': 'application/json';charset=UTP-8'
   },
   data: {
      name: 'test'
   }
   
   axios(options)
      .then(response => console.log(response))
}

AXIOS란?

특징

  • 운영 환경에 따라 브라우저간 XMLHttpRequest 객체 또는 Node.js의 HTTP API를 사용합니다.
  • ES6 Promise API를 사용합니다.
  • HTTP Methods를 사용합니다.
  • Request의 응답을 자동으로 JSON 형태로 만듭니다.

사용법

설치

yarn add axios

명령어 메소드를 사용시 'url', 'method', 'data' 속성을 config에서 지정할 필요가 없습니다.

GET / 데이터를 받을 때

GET 방식은 서버에서 어떠한 데이터를 받아서 보여줄 때 사용합니다.
- response는 json형태입니다.

  • 예시
    const getLists = async () => {
    	const { data } = await axios.get("요청할 주소")
    	// 이곳에서 받은 데이터 확인(JSON)
    }
  • 예시, try catch
    const getLists = async () => {
       try {
           const { data } = await axios.get("요청할 주소")
           console.log(data);
       } catch (error) {
           console.log(error);
       }
    }
  • 예시, then catch
    const getLists = async () => {
       axios.get("요청할 주소")
       .then(res => {
         console.log(res.data)
       }).catch(err => {
         console.log(err);
       })
    }

POST / 새로운 리소스를 생성할 때

POST 메소드의 두 번째 인자는 요청주소로 보낼 데이터 객체입니다.
- ex) 업로드, 로그인, 글 작성 등

  • 예시, then catch
const postList = async () => {
const { data } = await axios.post(
	"요청할 주소", 
	"보낼 값(객체)", 
	{
		headers: {
			'Content-type': 'application/json',
			'Accept': 'application/json'
		}
	}).then(res => {
    	console.log(res.data);
	}).catch(err => {
    	console.log(err)
	})
}
  • 예시, try catch
    const postList = async () => {
       try {
           const { data } = await axios.post("요청할 주소", {
    		 headers: {
               'Content-type': 'application/json',
               'Accept': 'application/json'
    		 }
    	   })
           console.log(data);
       } catch (error) {
           console.log(error);
       }
    }

DELETE / 데이터베이스에 저장된 내용을 삭제할 때

DELETE 메소드는 데이터베이스의 내용을 삭제합니다. .delete()는 두 번째 인자를 전달하지 않습니다.

  • 예시, try catch
const deleteList = async (listId) => {
	const { data } = await axios.delete(`요청할 주소/${listId}`)
}

PUT & PATCH / 저장된 내용을 수정할 때

PUT과 PATCH 메소드는 데이터베이스에 저장된 내용을 갱신하는 목적으로 사용됩니다.

PUT과 PACTH 차이점
PUT은?
=> 보낸 내용으로 리소스를 덮어씁니다.
PACTH는?
=> 보낸 내용으로 리소스의 일부를 변경합니다.

PUT과 PACTH는 HTTP 환경에서 대부분의 사람들이 약속한 문맥입니다. 즉, 반드시 PATCH와 PUT을 사용해야 하는 것은 아닙니다.

  • 예시
axios.put("요청할 주소", "덮어쓸 값", config)
axios.patch("요청할 주소", "일부만 바꿀 값", config)
profile
안녕하세요.

0개의 댓글