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' ) ;
このパッケージは、 intercepted
呼ばれる新しいグローバル イベント バスをwindow
オブジェクトに登録し、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
でアクセスできる反復可能なキーと値のオブジェクトを作成します。これは、元のエラー メッセージ構造を使用するよりも、すべてのメッセージを表示したり、単一フィールドのエラーを参照したりするために使用する方がはるかに簡単です。