-
axios interceptor카테고리 없음 2023. 8. 29. 22:27
interceptor가 필요한 이유
API를 호출하는 부분이 많다면 어떠한 이유로 호출하는 서버가 변경되었을 때 모두 변경을 해줘야하는 번거로움이 있다.
또한 console.log로 어떤 로깅을 할때 전부 다 코드를 넣어줘야 해서 엄청난 인적 리소스 낭비가 된다.interceptor란?
흐름을 가로채서 어떠한 코드 상의 관려를 할 수 있게 한다.
요청이 처리되기 전 , 응답이 성공, 실패가 처리되기전이 interceptor이다.
1. 요청 헤더 추가
2. 인증 관리
3. 로그 관련 로직 삽입
4. 에러 핸들링
실습
src폴더 -> axios폴더 -> api.ts
import axios from 'axios' const instance = axios.create({ baseURL: process.env.REACT_APP_SERVER_URL, }) export default instance
기본적으로 길었던 코드를 instance로 만들어준다.
<기존코드>
const fetchTodos = async () => { const {data} = await axios. get( `${process.env.REACT_APP_SERVER_URL}/todos` ); setTodos(data); };
<변경코드>
const fetchTodos = async () => { const {data} = await api. get( 'todos' ); setTodos(data); };
아래처럼 엄청 간결하게 사용할 수 있다.
적용할 수 있는 부분
요청할때 컨텐트 타입, 토큰관련 인증, 서버 응답 코드에 대한 오류처리, 통신의 시작과 종료에 대한 스피너나 프로그래스바를 구현할 수 있다.
import { SignUpProps, authCodeProps } from '../interfaces/axiosTypes' import api from './instance' // 이메일 인증 export const authCode = async (props: authCodeProps) => { // eslint-disable-next-line no-useless-catch try { const response = await api.post(`/api/users/authcode`, { email: props.email, }) return response.data } catch (error) { throw error } } // 인증번호 export const validation = async (props: validationProps) => { // eslint-disable-next-line no-useless-catch try { const response = await api.post(`/api/users/authcodevalidation`, { email: props.email, }) return response.data } catch (error) { throw error } } // 회원가입 export const signUp = async (props: SignUpProps) => { // eslint-disable-next-line no-useless-catch try { const response = await api.post(`/api/users/signup`, { nickname: props.nickname, email: props.email, password: props.password, }) return response.data } catch (error) { throw error } }
이렇게 공통ㅎ되게 사용되는게 많고 eslint때문에 에러나는게 있어서 주석도 추가함
crud.ts컴포넌트 만들어서
const postRequest = async (url: string, data: PostRequest) => { // eslint-disable-next-line no-useless-catch try { const response = await api.post(url, data) return response.data } catch (error) { throw error } }
넣었었으나 한솔님이 찾아봣을때 어차피 인터셉터과정에 필요한 코드이기 때문에
인터셉터에 추가해서 export함
그랬더니
import { AuthCodeProps, SignUpProps, ValidationProps } from '../interfaces/axiosTypes' import { postRequest } from './instance' // 이메일 인증 export const authCode = async (props: AuthCodeProps) => { return postRequest('/api/users/authcode', { email: props.email }) } // 인증번호 export const validation = async (props: ValidationProps) => { return postRequest('/api/users/authcode', { code: props.code }) } // 회원가입 export const signUp = async (props: SignUpProps) => { return postRequest('/api/users/signup', { nickname: props.nickname, email: props.email, password: props.password }) }
코드가 엄청 간결해진다.