일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- boolean
- false
- terminal
- API
- LIKELION
- HTML
- javascript
- STYLE
- http
- display
- block
- Absolute
- CSS
- js
- Project
- function
- object
- True
- ubuntu
- 프론트엔드스쿨
- 리액트
- 변수
- react
- position
- 조건문
- 선언
- array
- Inline
- 멋쟁이사자처럼
- 선택자
- Today
- Total
Jeden Tag, aufrichtig und lustig.
5. axios interceptors 본문

1. axios interceptors란?
axios interceptors는
axios가 then 또는 catch로 처리되기 전에 요청과 응답을 가로챌수 있다.
2. 사용하게 된 이유
투두리스트를 리액트로 만들면서
로그인 후 할일 목록이 나타나는 페이지로 이동하도록 하고,
axios를 활용해서 할일목록을 get하는 로직을 구성했다.
const access_token = localStorage.getItem("signInToken");
export const axiosAuthApi = axios.create({
baseURL: BASE_URL,
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
위 코드를 사용하니 새로고침 없이 할일목록이 get 되지 않고,
401 Unauthorized 에러가 발생했다.
ToDo.jsx:14 Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
콘솔을 통해 확인해보니
아래와 같이 로그인 전의 토큰 값이 null인 상태에서
토큰 값이 변동되지 않고
axios가 생성되서 발생한 문제인 것 같았다.

3. 해결과정
axios가 요청되기 전에 변동된 토큰값을 넣을 수 있는 방법을 찾았다.
그와중 axios interceptors가
axios의 요청과 응답을 가로챌수 있다는 것을 알게 되서 사용해보았다.
export const axiosAuthApi = axios.create({
baseURL: BASE_URL,
headers: {
"Content-Type": "application/json",
},
});
axiosAuthApi.interceptors.request.use(
(config) => {
const access_token = localStorage.getItem("signInToken");
config.headers.Authorization = `Bearer ${access_token}`;
return config;
},
(error) => {
console.log("에러", error);
return Promise.reject(error);
}
);
활용하여 로그인 후 변동 된 토큰을
axios를 통한 http 요청 전 헤더에 넣을 수 있게 되어
새로고침 없이 할일목록이 잘 받아와졌다.

4. 결론
인터셉터를 활용하여
axiosAuthApi.interceptors.request.use() 함수를 사용하면
모든 axios요청에 대해 요청 전 인증 토큰을 요청 헤더에 추가 할 수 있다.
코드의 반복도 줄이고 유지 보수성을 높이는 장점까지 있으니 인터셉터를 적절히 활용해보자.
참고 사이트
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
'das Studium' 카테고리의 다른 글
7. code EACCES 에러 (0) | 2023.04.10 |
---|---|
6. debouncing (0) | 2023.04.01 |
4. remote: fatal error in commit_refs (0) | 2023.03.28 |
3. npm & module (0) | 2023.03.07 |
2. 생성자 함수와 일반 함수의 차이점 (0) | 2023.02.23 |