Axios 공식 홈페이지 따라하기
Axios 공식 홈페이지 따라하기 (6) - Config 기본값
vitamin3000
2025. 2. 5. 21:02
Config 기본 값
모든 요청에 적용될 config 기본 값을 지정할 수 있다.
전역 Axios 기본값
axios.defaults.baseURL = 'http://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'
})
// 인스턴스를 만든 후 기본 값 변경하기
intance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Config 우선 순위
1. 요청의 config 인자
2. 인스턴스의 defaults 속성
3. lib/defaults.js 라이브러리
// 라이브러리에서 제공하는 config 기본값을 사용하여 인스턴스 만들기
// 이떄 timeout의 값은 라이브러리 기본값인 0이다.
const instance = axios.create();
// 라이브러리에 대한 timeout 값 재정의
// 이제 모든 요청은 시간 초과 전 2.5초 대기하는 인스턴스를 사용
instance.defaults.timeout = 2500;
// 시간이 오래 걸리는 요청에 대한 timeout 값 정의
instance.get('/longRequest', {
timeout: 5000
});