React - 비동기 통신

Jinwoo Ma·2023년 12월 1일

React

목록 보기
15/17
post-thumbnail

1. Axios

공식문서에 따르면 node.js와 브라우저를 위한 Promise 기반 http 클라이언트

Axios 설치

yarn add axios

Get

서버의 데이터를 조회할 때 사용

axios.get(url[, config])

url에는 서버의 url, config에는 기타 여러가지 설정이 들어간다.

Post

서버에 테이터를 추가할 때 사용

axios.post(url[, data[, config]])

Delete

저장되어 있는 데이터 삭제 요청

axios.delete(url[, config])

Patch

데이터 수정을 서버에 요청

axios.patch(url[, data[, config]])  

axios 에러 처리

axios는 error handling에서 매우 친절하다.

const url = "https://jsonplaceholder.typicode.com/todos";

// axios 요청 로직
axios
  .get(url)
  .then((response) => console.log(response.data))
	.catch((err) => {

		// 오류 객체 내의 response가 존재한다 = 서버가 오류 응답을 주었다	
		if (err.response) {
			
	    const { status, config } = err.response;
	
			// 없는 페이지
	    if (status === 404) {
	      console.log(`${config.url} not found`);
	    }

			// 서버 오류
	    if (status === 500) {
	      console.log("Server error");
	    }
	
		// 요청이 이루어졌으나 서버에서 응답이 없었을 경우
	  } else if (err.request) {
	    console.log("Error", err.message);
		// 그 외 다른 에러
	  } else {
	    console.log("Error", err.message);
	  }
	});

0개의 댓글