vue axios interceptors
0.3.1
Vue
와 함께 Axios
사용할 때 전체적으로 ajax 오류를 포착하고 처리합니다.
npm install vue-axios-interceptors --save
// or
yarn add vue-axios-interceptors
// Make sure you import this package after you've imported Vue:
window . Vue = require ( 'vue' ) ;
require ( 'vue-axios-interceptors' ) ;
// Make sure the axios package is available globally on the window object:
window . axios = require ( 'axios' ) ;
패키지는 window
객체에 intercepted
라는 새로운 전역 이벤트 버스를 등록하고 ajax 호출로 인해 오류가 발생할 때 여러 이벤트를 내보냅니다. 이러한 이벤트를 쉽게 수신하여 원활한 오류 처리 워크플로를 구축할 수 있습니다(예: 오류 메시지 표시를 담당하는 전역 구성 요소).
// ErrorMessages.vue
mounted ( ) {
window . intercepted . $on ( 'response' , data => {
console . log ( data ) ; // { status: 404, code: 'Not found', body: null }
// Display the message.
} ) ;
}
예를 들어 4xx 응답을 5xx 응답과 다르게 처리하려는 경우 특정 상태 코드 및 응답 범주를 수신할 수도 있습니다.
// Listen for any intercepted responses.
window . intercepted . $on ( 'response' , data => {
//
} ) ;
// Listen for any intercepted responses under the Client Error category (4xx).
window . intercepted . $on ( 'response:client-error' , data => {
//
} ) ;
// Listen for any intercepted responses under the Server Error category (5xx).
window . intercepted . $on ( 'response:5xx' , data => {
//
} ) ;
// Listen for a specific status.
window . intercepted . $on ( 'response:404' , data => {
//
} ) ;
// Listen for a specific HTTP code.
window . intercepted . $on ( 'response:unprocessable-entity' , data => {
//
} ) ;
상태 코드의 전체 목록을 보려면 https://httpstatuses.com/을 방문하세요.
백엔드로 Laravel >=5.5를 사용하고 있다면 운이 좋을 것입니다. 서버가 422
응답(일반적으로 유효성 검사 오류)을 반환하는 경우 패키지는 반환된 실패를 data.body
에서 액세스할 수 있는 반복 가능한 키-값 객체로 자동 구문 분석합니다. 이는 원래 오류 메시지 구조보다 모든 메시지를 표시하거나 단일 필드 오류를 참조하기 위해 사용하는 것이 훨씬 더 간단합니다.