happy coding

[js] axios 탐방 - 2 본문

self study/library

[js] axios 탐방 - 2

yeoonii 2024. 3. 14. 09:16

1. 라이브러리 문서를 볼 때 뭐부터 봐야할지 모른다.

그래서 google에 대충 axios best practice를 검색했다. 그렇게 얻은 내용을 아래에 정리했다.

Pros and Cons of Using Axios

- pros : Simplicity, Backwards compatibility, Mature library with lots of features

- cons : Too sophisticated for small apps, bloats bundle size, third party

 

2. config 기본값

config : configuration(환경 설정); 프로그램의 매개 변수나 초기 설정 등을 구성하는 데 사용하는 파일로 XML, JSON 로 저장되기도 한다.

전역 axios 기본값

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

 

커스텀 인스턴스 기본값

// 인스턴스를 생성할때 config 기본값 설정하기
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 인스턴스를 만든 후 기본값 변경하기
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

config 우선 순위 (lib/defaults.js)

// 라이브러리에서 제공하는 config 기본값을 사용하여 인스턴스 만들기
// 이 때 timeout 값은 라이브러리의 기본값인 '0'입니다.
const instance = axios.create();

// 라이브러리에 대한 timeout 값 재정의
// 이제 모든 요청은 시간 초과 전 2.5초 대기하는 인스턴스를 사용합니다.
instance.defaults.timeout = 2500;

// 시간이 오래 걸리는 요청에 대한 timeout 값 재정의
instance.get('/longRequest', {
  timeout: 5000
});

https://daily.dev/blog/a-guide-to-writing-clean-api-calls-using-axios

 

A Guide To Writing Clean API Calls Using Axios

Write better and more readable frontends using Axios.

daily.dev

>> clean api call 이란? 

'self study > library' 카테고리의 다른 글

[js] postgreSQL - ... (spread Operator)  (0) 2024.04.13
[js] axios 탐방 - 1  (0) 2024.03.12
Comments