文章目录[隐藏]
实现目标
- 设置全局请求头,用于传输 token
- 设置响应拦截器,实现以下功能:
- 当响应体不是 json 的时候,弹出错误提示
- 处理 laravel 响应的异常
- 实现特定功能(如让浏览器跳转的响应)
- 在请求发起位置 catch 回调函数中根据失败原因不同而进行不同操作(通过 flag 实现)
特定功能(如让浏览器跳转的响应)
基本思路(不可行)
自己创建一个 http status code ,用于表示特定功能,如 200301 表示让浏览器跳转。
但是,laravel 返回响应,不能设置自己创建的 http status code,如 200301,
会抛出 500 异常:The HTTP status code \”200301\” is not valid.
更优思路
代码实现
bootstarp.js
/** * 初始化 anxios * 加入 csrf_token 到请求头、设置响应拦截器 */ window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; let token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; } else { console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); }
/** * 为所有 axios 请求添加一个响应拦截器 */ axios.interceptors.response.use(function (response) { /*http status code 为 2xx*/ if (typeof (response.data) === 'object') { /*响应体是 json*/ /*根据自定义的 data.status 来实现特定功能(如让浏览器跳转的响应)*/ switch (response.data.status) { case 302: // 浏览器跳转 window.location = response.data.url; break; case 3021: // 弹出提示后再跳转 alert(response.data.message); window.location = response.data.url; break; default: // 默认的就弹出提示 成功信息就行 toastr.success(response.data.message); } } else { /*响应体不是 json*/ toastr.error('服务器错误'); // 这样 不会执行发起请求位置的 then return Promise.reject('服务器错误'); } return response; }, function (error) { /* http status code 不为 2xx*/ if (typeof (error.response.data) === 'object') { /* 响应体是 json*/ /*根据特定的 http status code 来特定处理异常*/ switch (error.response.status) { case 401: // 【异常】未登录 alert('请先登录!'); window.location.href = route('login'); break; default: // 未特定处理的异常,简单弹出提示就好了 toastr.error(error.response.data.message); } } else { // 响应体不是 json toastr.error('服务器错误'); } // 这样 不会执行发起请求位置的 then return Promise.reject(error); });