-
Axios 요청 중 Interceptor프론트엔드 2022. 8. 30. 20:02
Interceptor란?
REST API 요청에서의 공통작업
모든 사용자들에게 오픈되어 있는 API요청도 있겠지만 많은 API들이 OAuth2 인증 후
발급받는 Access token 을 Http Header에 담아 API 접근을 하도록 요구한다. 그렇다면
일일히 API 요청할 때 Access token을 담는 작업을 해야하는 상황이 오게 된다.
이러한 상황에 적용할 수 있는 Pattern이 바로 Intercepter다.
Interceptor 이름그대로 사용자의 요청을 가로채는 역할을 한다.
조금 더 세부적으로는
then이나 catch로 처리되기 전에 요청이나
응답을 가로챌 수 있다. 따라서 이를 이용하면 Axios를 이용해 API로
통신할 때 항상 사용하는 baseURL이나 headers와 같은 부분을 한번에
모든 Axios 요청에 관해처리해 둘 수 있다.
요약하면 보내는것과 서버에서 받은 응답을 화면(컴포넌트)단에서 처리하기전에
추가로직을 넣을수 있는 API로 얘기할 수 있다.
// 요청 인터셉터 추가 axios.interceptors.request.use( function (config) { // 요청을 보내기 전에 수행할 일 // ... return config; }, function (error) { // 오류 요청을 보내기전 수행할 일 // ... return Promise.reject(error); } ); // 응답 인터셉터 추가 axios.interceptors.response.use( function (response) { // 응답 데이터를 가공 // ... return response; }, function (error) { // 오류 응답을 처리 // ... return Promise.reject(error); } );
REST API의 baseURL과 headers 설정하기
예를 들어서 baseURL은 http://localhost:3000/ 이고,
headers에는 Authorization과 Content-Type을 넣어줘야하는 상황일 때
interceptors 적용하지 않았을 때
앞서 말한 axios를 이용한 모든 REST API 요청에서 API 주소와 필요한 headers를
변수로 사용한다 하더라도 항상 넣어줘야해서 귀찮은 일을 반복하는 일이 생긴다.
baseURL과 headers를 변수로 사용
const baseURL = "http://localhost:3000/"; const options = { headers: { Authorization: `Bearer ${process.env.REACT_APP_KEY}`, "Content-Type": "application/json", }, };
get
const getData = async () => { await axios.get(baseURL, options); };
post
const postData = async () => { await axios.post(baseURL, { data }, options); };
patch
const patchData = async (todo) => { await axios.patch(`${baseURL}/${todo.id}`, { data }, options); };
delete
const deleteData = async (todo) => { await axios.delete(`${baseURL}/${todo.id}`, options); };
interceptors 적용 시
이번엔 interceptors를 이용해 모든 axios 요청에 baseURL과 headers를 넣어줬기 때문에
이제 axios 요청을 할 때마다 baseURL과 headers를 넣어줄 필요가 없다.
.
axios.defaults.baseURL = "http://localhost:3000/"; axios.interceptors.request.use(async (config) => { if(!config.headers["Authorization"]){ config.headers["Authorization"] = `Bearer ${process.env.REACT_APP_KEY}`; } config.headers["Content-Type"] = "application/json"; return config; });
get
const getData = async () => { await axios.get("/"); };
post
const postData = async () => { await axios.post("/", { data }); };
patch
const patchData = async (todo) => { await axios.patch(`/${todo.id}`, { data }); };
delete
const deleteData = async (todo) => { await axios.delete(`/${todo.id}`); };
출처: Axios Interceptors로 API 관리 | Today DOWON Learned (2dowon.github.io)
Axios Interceptors로 API 관리
TIL
2dowon.github.io
'프론트엔드' 카테고리의 다른 글
로그인 구현중 input태그에 type="password" 에 눈 모양 없애기(edge 브라우저) (0) 2022.09.03