인터셉터란?
인터셉터는 1.요청하기 직전, 2. 응답을 받고 then, catch로 처리 직전에 가로챌 수 있다.
인터셉터는 모든 소스 내 axios가 들어간 부분에 공통적으로 적용이 되어야 한다.
따라서 global config를 해줘야한다.
여러가지 인터셉터를 구현하는 방법이 있지만,
axios.interceptors를 내 web application에 전역으로 설정하여 구성하였다.
(다음 블로그 참고 :: https://ayoteralab.tistory.com/entry/Vuejs-21-axios-interceptors)
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
function (config) {
// 요청 바로 직전
// axios 설정값에 대해 작성합니다.
console.log('request interceptor!!!!')
return config;
}, function (error) {
// 요청 에러 처리를 작성합니다.
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(
function (response) {
/*
http status가 200인 경우
응답 바로 직전에 대해 작성합니다.
.then() 으로 이어집니다.
*/
console.log('response interceptor!!!!')
return response;
}, function (error) {
/*
http status가 200이 아닌 경우
응답 에러 처리를 작성합니다.
.catch() 으로 이어집니다.
*/
return Promise.reject(error);
});
export default axios;
plugin을 import 후 주석을 참고하여 request, response 에 해당하는 interceptors도 포함하여 작성하자.
작성 후 main.js 파일에 새로추가한 axios.js 파일을 improt 하자 import axios from '@/plugins/axios';
인터셉터 적용하기
- request에서 인터셉터로 header에 토큰을 실어주었고
- 기존의 catch에서 error를 처리하지 않고 response에서 error를 처리하였다
- 단 login부분 url은 예외처리를 하여 따로 error처리를 구현하였다 (아래코드 참조)
axios.interceptors.response.use(function (response) {
console.log('response interceptor!!!!')
return response;
}, function (error) {
console.log("response "+ error.response.data.path)
if(error.response.data.path === "/authenticate"){
console.log("exception Login page")
}
else if(error.response.status===401) {
store.commit('loginCheck', error.response.status)
}
return Promise.reject(error);
});
login 페이지에서는 login에서 구현한 error처리가 수행된다.
여러가지 인터셉터 구현방법
아래 블로그를 참고하여 작성하였고 내용이 잘 정리되어있다.
[Vue.js] 21. axios interceptors
Spring Boot에서 기존에 JWT를 통한 인증을 포함하는 RestAPI를 구현할 때, Interceptor라는 것이 있었습니다. 이 기능은 httpRequest와 httpResponse를 진행하기 전에 잠시 application에서 가로채서 특정 동작을..
ayoteralab.tistory.com
Axios 다양하게 활용하기: interceptor - Third9's Lounge
Axios 다양하게 활용하기: interceptor 💡 새로운 서비스를 개발하면서 개인적으로 정리한 내용들입니다. 글이 깔끔하지 않을 수 있습니다. 📔 이전글 보기: Axios 다양하게 활용하기: async/await사용 Ax
third9.github.io
axios 인터셉터로 API 관리하기
axios interceptors로 API를 공통 관리해 봅시다. axios 인터셉터는 1.요청하기 직전, 2. 응답을 받고 then, catch로 처리 직전에 가로챌 수 있습니다.
velog.io
'Vue > Vue' 카테고리의 다른 글
doFilter 특정 URL 제외시키기 (0) | 2021.12.23 |
---|---|
(SignUp-1) 회원가입 구현하기 (0) | 2021.12.16 |
(Login-2) 로그인 인증, 인증 만료 (0) | 2021.12.10 |
(Login-1) JWT 로그인 방식 (0) | 2021.12.08 |
10. 새로고침시 Vuex 상태 유지 (vuex-persistedstate) (0) | 2021.12.08 |