Axios API

김종현·2023년 3월 24일
0

Node.js

목록 보기
3/8

Axios API

-웹 브라우저와 Node.js를 위한 HTTP 비동기 통신 라이브러리
-쉽게 말해 백엔드와 프론트엔드 간 통신을 쉽게 하기 위해 사용되는 것으로 Ajax처럼 사용되는 것
-Ajax: Asynchronous JavaScript and XML

  • 비동기 자바스크립트란 의미.
  • 브라우저가 가지고 있는 XMLHttpRequest 객체를 이용하여 화면 전체를 새로 고침 하지 않고 변경된 일부 데이터만 로드하는 비동기 처리가 가능.

-Axios는 Ajax와 유사하며 API를 이용한 통신을 할 때 주로 사용, Promise를 기반으로 만들어진 라이브러리.

Fetch vs Axios

1)Fetch의 경우 자바스크립트에 내장되어 있기 때문에 별도의 import나 설치가 필요하지 않다. 하지만 Axios의 경우 간단하지만 설치 과정이 필요합니다.
2)Fetch는 일부 예전의 인터넷 익스플로러 버전에서 지원하지 않는 경우가 있어, Axios가 Fetch보다 브라우저 호환성이 뛰어나다.
3)Fetch에서는 지원하지 않는 JSON 자동 변환, 응답 시간 초과 설정 기능 등을 Axios에서 지원해준다.

-자신의 개발 상황(지원하는 브라우저, 기타 다른 패키지 등등)에 맞는 라이브러리를 선택하는 것이 필요

API

-Application Programming Interface의 줄임말로 다양한 응용 프로그램에서 사용할 수 있도록, 운영 체제나 프로그래밍 언어가 제공하는 기능을 제어할 수 있게 만든 인터페이스
-프로그램과 프로그램을 연결해 주는 다리 역할.

[손님] -주문-> [점원(API)] -주문-> 요리사

[손님] <-요리- [점원(API)] <-요리- 요리사

Axios와 CRUD

C : Create(생성) - POST
R : Read(조회) - GET
U : Update(수정) - PUT
D : Delete(삭제) - DELETE

Axios 사용법

index.html에 아래 두 스크립트를 추가해주면 axios 라이브러리를 손쉽게 사용

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

POST 새로운 자원을 생성 : CREATE

axios.post(url, data 객체)
//선언한 객체와 url을 전달, 전달한 객체에 대해 결과를 받아옴.

//emial과 pw를 전달해 token 값을 받는 API
function axiosPost(){
	const token = document.getElementById("token");
    const login = { email: "eve.holt@reqres.in", password: "cityslicka" };
    
    axios.post("https://reqres.in/api/login", login).then((response) => {
    let res = response.data.token;
    token.innerHTML = res;
  });
}

GET 자원을 요청 : READ

axios.get(url)
//
function axiosGet() {
  const name = document.getElementById("name");
  const email = document.getElementById("email");

  // axios.get을 호출하고 반환되는 데이터를 확인하세요.
  // 확인한 데이터에서 이름과 이메일을 출력 결과와 같이 출력하세요.
  axios.get("https://reqres.in/api/users/2").then((response) => {
    let res = response.data.data;
    name.innerHTML = res.first_name + " " + res.last_name;
    email.innerHTML = res.email;
  });
}

PUT 자원을 갱신 : UPDATE

axios.put(url, data 객체)
//
function axiosPut() {
  const name = document.getElementById("name");
  const email = document.getElementById("email");
  const updateDate = document.getElementById("update_date");
//수정할 데이터 객체 선언
	const updateData = {
    	first_name: "White",
    	last_name: "Rabbit",
    	email: "alice@elice.io",
 		 };
//axios.put을 호출하고 result에 반환되는 사용자 데이터를 저장
axios.put("https://reqres.in/api/users/2", updateData).then((response) => {
    let res = response.data;
    name.innerHTML = res.first_name + " " + res.last_name;
    email.innerHTML = res.email;
    updateDate.innerHTML = res.updatedAt;
  });
}

DELETE 자원을 삭제 : DELETE

axios.delete(url)
//
function axiosDelete() {
  const status = document.getElementById("status");

//axios.delete를 호출하고 반환되는 status를 확인
//삭제 결과 반환되는 status를 통해 처리 결과를 확인.
//삭제 후 별다른 데이터를 넘겨주지는 않음
  axios.delete("https://reqres.in/api/users/2").then((response) => {
    console.log(response);
    status.innerHTML = response.status;
  });
}
profile
나는 나의 섬이다.

0개의 댓글