axios interceptors

mangojang·2023년 4월 18일
0

✍️ 로그인에 성공하고, api 요청을 할 때, 매번 요청 할 때마다 인증 문제로 토큰을 헤더에 넣어서 보내야 했는데, 이 상황 이 불편하여 개선하고자 찾아보다가 발견하였다. interceptor의 기본 정의와 사용 방법 그리고 필자의 상황에 따른 적용 방법을 기록해 보았다.

interceptor란?

interceptor = 가로챈다” 라는 뜻으로 axios로 요청을 보내기전 or 받기 전에 가로채어서 설정한 행동을 실행한다.

기본 사용 방법

// 요청시
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
		// 요청 보내기 전 실행해야 할 코드 추가
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// 응답시
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
		// 응답 받을 때 추가로 적용 해야할 코드 추가
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

상황

api 요청 시, 매번 인증 관련 토큰을 localStorage에서 가져와서 header 에 넣어서 보내야 되는 상황. 중복 코드를 줄이고자, 전역으로 이를 설정하려고 한다.

적용

axios.interceptors.request.use(function (config) {
    config.headers.Authorization = `Bearer ${localStorage.getItem('todo')}`
    return config
  }, function (error) {
    return Promise.reject(error)
})

참고 문헌

profile
한 걸음 한 걸음 계속 걷는 자가 일류다

0개의 댓글