개요
Axios는 Promise 기반의 HTTP 클라이언트로, 브라우저와 Node.js에서 모두 사용할 수 있습니다. Axios는 요청(Request)과 응답(Response)을 가로챌 수 있는 인터셉터(Interceptors) 기능을 제공합니다. 인터셉터를 사용하면 요청이나 응답을 변경하거나, 요청 전후에 추가 작업을 수행할 수 있습니다.
1. Interceptors의 개념
인터셉터는 Axios 요청이나 응답을 가로채고, 해당 요청 또는 응답을 처리하는 코드 조각을 추가할 수 있게 해줍니다. 이 기능은 인증 토큰을 자동으로 첨부하거나, 모든 응답을 로깅하는 등 여러 가지 용도로 사용할 수 있습니다.
2. Interceptors의 종류
- Request Interceptors: HTTP 요청을 서버로 보내기 전에 실행됩니다.
- Response Interceptors: 서버로부터 HTTP 응답을 받은 후, then이나 catch로 처리하기 전에 실행됩니다.
3. Request Interceptors 사용법
Request Interceptors는 요청이 서버로 보내지기 전에 수행할 작업을 정의할 수 있습니다.
import axios from 'axios';
// 요청 인터셉터 추가
axios.interceptors.request.use(
function (config) {
// 요청을 보내기 전에 작업 수행
config.headers.Authorization = 'Bearer token';
console.log('Request Interceptor: ', config);
return config;
},
function (error) {
// 요청 오류가 있는 경우 작업 수행
return Promise.reject(error);
}
);
위 예제에서 Authorization 헤더에 토큰을 추가하고 있습니다. 이 인터셉터는 모든 요청에 대해 실행됩니다.
4. Response Interceptors 사용법
Response Interceptors는 응답을 받은 후, then이나 catch로 처리되기 전에 작업을 수행할 수 있습니다.
import axios from 'axios';
// 응답 인터셉터 추가
axios.interceptors.response.use(
function (response) {
// 응답 데이터를 가공하거나 로그를 남기는 작업 수행
console.log('Response Interceptor: ', response);
return response;
},
function (error) {
// 응답 오류가 있는 경우 작업 수행
return Promise.reject(error);
}
);
위 예제에서는 응답을 로그로 남기고 있습니다. 모든 응답에 대해 이 인터셉터가 실행됩니다.
5. Interceptors의 사용 예제
- 토큰 추가 및 에러 처리
import axios from 'axios';
// 요청 인터셉터
axios.interceptors.request.use(
function (config) {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
// 응답 인터셉터
axios.interceptors.response.use(
function (response) {
return response;
},
function (error) {
if (error.response && error.response.status === 401) {
// 인증 오류 처리 (예: 로그아웃 처리)
console.error('Unauthorized, logging out...');
localStorage.removeItem('token');
}
return Promise.reject(error);
}
);
위 예제에서는 요청 인터셉터를 사용하여 모든 요청에 토큰을 자동으로 추가하고, 응답 인터셉터를 사용하여 401 오류(인증 오류)를 처리합니다.
- 로딩 인디케이터
import axios from 'axios';
import { store } from './store'; // Vuex store 예제
// 요청 인터셉터
axios.interceptors.request.use(
function (config) {
store.dispatch('setLoading', true); // 로딩 상태를 true로 설정
return config;
},
function (error) {
store.dispatch('setLoading', false); // 로딩 상태를 false로 설정
return Promise.reject(error);
}
);
// 응답 인터셉터
axios.interceptors.response.use(
function (response) {
store.dispatch('setLoading', false); // 로딩 상태를 false로 설정
return response;
},
function (error) {
store.dispatch('setLoading', false); // 로딩 상태를 false로 설정
return Promise.reject(error);
}
);
위 예제에서는 요청이 시작될 때 로딩 인디케이터를 표시하고, 요청이 완료되면 로딩 인디케이터를 숨깁니다.
6. Interceptors 관리
인터셉터를 추가하면 해당 인터셉터는 모든 Axios 인스턴스에 대해 전역적으로 적용됩니다. 특정 Axios 인스턴스에만 인터셉터를 적용하고 싶다면 인스턴스를 생성하고 해당 인스턴스에 인터셉터를 추가할 수 있습니다.
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// 인스턴스에 인터셉터 추가
instance.interceptors.request.use(
function (config) {
// 요청 인터셉터 작업
return config;
},
function (error) {
return Promise.reject(error);
}
);
instance.interceptors.response.use(
function (response) {
// 응답 인터셉터 작업
return response;
},
function (error) {
return Promise.reject(error);
}
);
7. Interceptors 제거
인터셉터를 제거하려면 해당 인터셉터의 ID를 사용하여 제거할 수 있습니다.
import axios from 'axios';
const myInterceptor = axios.interceptors.request.use(function (config) {
return config;
});
// 인터셉터 제거
axios.interceptors.request.eject(myInterceptor);
요약
- Interceptors는 Axios 요청과 응답을 가로채고, 추가 작업을 수행할 수 있게 해주는 강력한 기능입니다.
- Request Interceptors는 요청이 서버로 보내지기 전에 실행됩니다.
- Response Interceptors는 서버로부터 응답을 받은 후, then이나 catch로 처리되기 전에 실행됩니다.
- Interceptors를 사용하여 인증 토큰 추가, 에러 처리, 로딩 인디케이터 관리 등의 작업을 할 수 있습니다.
- 특정 Axios 인스턴스에만 인터셉터를 적용할 수 있으며, 필요 시 인터셉터를 제거할 수도 있습니다.
이를 통해 비동기 요청을 더욱 효율적이고 체계적으로 관리할 수 있습니다.
'Javascript' 카테고리의 다른 글
| [Javascript] async와 await의 개념과 사용법 (0) | 2024.07.16 |
|---|---|
| [Javascript] 화살표 함수(Arrow Function) 이해하기 (0) | 2024.06.11 |
| [Javascript] 스프레드 연산자와 레스트 파라미터 이해하기 (0) | 2024.06.11 |
| [Javascript] 클로저(Closure) 이해하기 (0) | 2024.06.11 |
| [Javascript] 웹팩(Webpack)이란? (1) | 2024.06.05 |