11. [클라이언트] 서버와 통신하기 (1) Axios 의 설명
https://dive-into-frontend.tistory.com/200
8.[클라이언트] - Redux-Toolkit ( Typescript )을 이용해, DB의 값 가져오기 (Thunk 액션 생성자 )
DB 에 있는 값을, Store 로 직접 가져오는 Thunk 액션 생성자를 사용해본다. 준비물 typescript react-redux redux-toolkit 데이터베이스 서버 서버 1. Slice 의 생성 store 폴더 안에 slice 를 생성한다. < store / user-di
dive-into-frontend.tistory.com
Get 요청은 Action 생성자에서 사용해보았다.
현재 바꿔야 할 것은 두가지이다.
1. fetch 대신 Axios 를 사용해본다.
2. apis 폴더를 만들어, 서버에 요청하는 코드들을 아웃소싱한다.
그렇기에 우선 Axios 에 대해 알아보자.
https://axios-http.com/kr/docs/api_intro
Axios API | Axios Docs
Axios API Axios API 레퍼런스 axios에 해당 config을 전송하면 요청이 가능합니다. axios(config) axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); axios({ method: 'get', url: 'http://bit.ly/
axios-http.com
axios 는 Promise 기반 HTTP 클라이언트 라이브러리
즉, 비동기식 HTTP 요청을 해주는 도구 정도 되겠다.
특징으로는
브라우저에서 사용할 수 있도록 XMLHttpRequests 를 생성 하고
Node 에서는 http 요청을 생성할 수 있게 한다.
Promise API 를 지원한다.
등등이 있겠다.
사용하면서 가장 중요하게 느낀 특징은
JSON 자동변환 **
요청 및 응답 인터셉트 **
요청 및 응답 데이터 변환 **
Config 를 사용한 기본 요청 생성 가능 **
1. JSON 데이터 자동변환
fetch 의 경우
const response = await ...
const responseData = await response.json() ...
처럼 들어온 json 데이터를 자바스크립트 데이터로 변환하는 과정이 필요하지만
axios 의 경우
const response = await axios(...)
하면 끝난다. 자동으로 자바스크립트 코드로 변환된다.
2. 요청 및 응답 인터셉트
인터셉트를 통해 요청 혹은 응답 값을 보내거나 받기 직전!
그 값을 캐치해서 오류처리 등을 할 수 있다.
https://axios-http.com/kr/docs/interceptors
인터셉터 | Axios Docs
인터셉터 then 또는 catch로 처리되기 전에 요청과 응답을 가로챌수 있습니다. axios.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); }); axios.interceptors.response.use(f
axios-http.com
3. 요청 및 응답 데이터 변환
axios 는 자동으로 응답 데이터를 변환시킨다.
** 응답데이터 (response)
config : ...
data : 받은 데이터
headers : 헤더
request : ...
status : 코드
statusText : "OK"
응답을 받으면 자동으로 이런 형식으로 들어오게 된다.
4. Config 를 통한 기본 요청 생성
config 를 통해 기본적인 요청을 생성할 수 있다.
이는 fetch 가 항상 Headers 값과 Assignment 값, url 값을 입력해주어야 하는 번거로움을 타파하고
편하고 가동성 좋게 만들 수 있다.
import axios from "axios";
const axiosConfig = {
baseURL: "http://localhost:5000/api/diary/",
timeout: 1000000,
headers: { "Content-Type": "application/json" },
};
export const client = axios.create(axiosConfig);
이런식으로 기본 요청을 생성하면
import { client } from "../util/axios";
export const getUserDairy = async (userEmail: string) => {
const response = await client.get(`/${userEmail}`);
return response.data.data;
};
export const insertUserDiary = async (userInput: TypeUserDiary) => {
const response = await client.post("/insert", userInput);
return response.data;
};
...
이렇게 가뿐하게 사용 할 수 있다.
중복되는 코드들을 전부 없애고 가동성 좋은 라우터처럼 만드는 것이 가능하다.
* post 의 두번째 파라미터는 body 값이다
다음 시간에 실제로 적용해보자.