REST API

심채운·2022년 8월 14일
0

cs

목록 보기
10/15

Axios

Axios는 브라우저, Node.js를 위해서 만들어진 Promise API를 활요하는 HTTP 비동기 통신 라이브러리 이다.
(백엔드와 프론드엔드간에 통신을 위해서 만들어진 AJAX도 더불어 사용하기도 한다.)

GET 요청

//async / await를 사용할 경우 함수 또는 메서드 앞에 async 키워드를 사용하고

//내부에 async 키워드를 사용해 비동기 통신 요청을 처리합니다.

//async / await는 오류 디버깅을 위해 try/catch 구문을 사용합니다.
async function getUser() { // async 사용
  try { // try
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) { //catch
    console.error(error);
  }
}

Post 방식

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Delete 방식

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

Patch 방식

export const __patchTodo = createAsyncThunk(
  "Detail/__patchTodo",
  async (payload, thunkApi) => {
    try {
      const targetId = payload.id;
      const newBody = { body: payload.newBody };
      const data = await axios.patch(todoServer + `/${targetId}`, newBody);
      return thunkApi.fulfillWithValue(data.data);
    } catch (error) {
      return thunkApi.rejectWithValue(error.message);
    }
  }
);

Fetch vs Axios

Fetch와 Axios 둘 다 HTTP 요청을 처리하기 위한 자바스크립트의 라이브러리이다.
Fetch의 경우 자바스크립트에 내장되어 있기 때문에 별도의 import나 설치가 필요하지 않다.
Axios의 경우 설치 과정이 필요하다.
Fetch는 일부 예전의 인터넷 익스플로러 버전에서 지원하지 않는 경우가 있어, Axios가 Fetch보다 브라우저 호환성이 뛰어나다.
Fetch에서는 지원하지 않는 JSON 자동 변환, 응답 시간 초과 설정 기능 등을 Axios에서 지원해준다.
자신의 개발 상황(지원하는 브라우저, 기타 다른 패키지 등등)에 맞는 라이브러리를 선택하는 것이 필요하다.

profile
불가능, 그것은 사실이 아니라 하나의 의견일 뿐이다. - 무하마드 알리

0개의 댓글