怎么在vue+axios 前端實現攔截?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
創新互聯是專業的鐵山網站建設公司,鐵山接單;提供網站設計、成都做網站,網頁設計,網站設計,建網站,PHP網站建設等專業做網站服務;采用PHP框架,可快速的進行鐵山網站開發網頁制作和功能擴展;專業做搜索引擎喜愛的網站,專業的做網站團隊,希望更多企業前來合作!
Axios攔截器配置
main.js
//定義一個請求攔截器 Axios.interceptors.request.use(function(config){ store.state.isShow=true; //在請求發出之前進行一些操作 return config }) //定義一個響應攔截器 Axios.interceptors.response.use(function(config){ store.state.isShow=false;//在這里對返回的數據進行處理 return config })
分別定義一個請求攔截器(請求開始時執行某些操作)、響應攔截器(接受到數據后執行某些操作),之間分別設置攔截時執行的操作,改變state內isShow的布爾值從而控制loading組件在觸發請求數據開始時顯示loading,返回數據時隱藏loading
特別注意:這里有一個語法坑(我可是來來回回踩了不少次)main.js中調取、操作vuex state中的數據不同于組件中的this.$store.state,而是直接store.state 同上面代碼
一、路由攔截使用
router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { // 判斷該路由是否需要登錄權限 if (store.state.token) { // 通過vuex state獲取當前的token是否存在 next(); } else { next({ path: '/login', query: {redirect: to.fullPath} // 將跳轉的路由path作為參數,登錄成功后跳轉到該路由 }) } } else { next(); } })
二、攔截器使用
要想統一處理所有http請求和響應,就得用上 axios 的攔截器。通過配置http response inteceptor,當后端接口返回401 Unauthorized(未授權),讓用戶重新登錄。
// http request 攔截器 axios.interceptors.request.use( config => { if (store.state.token) { // 判斷是否存在token,如果存在的話,則每個http header都加上token config.headers.Authorization = `token ${store.state.token}`; } return config; }, err => { return Promise.reject(err); }); // http response 攔截器 axios.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: // 返回 401 清除token信息并跳轉到登錄頁面 store.commit(types.LOGOUT); router.replace({ path: 'login', query: {redirect: router.currentRoute.fullPath} }) } } return Promise.reject(error.response.data) // 返回接口返回的錯誤信息 });
三、實例
/** * http配置 */ // 引入axios以及element ui中的loading和message組件 import axios from 'axios' import { Loading, Message } from 'element-ui' // 超時時間 axios.defaults.timeout = 5000 // http請求攔截器 var loadinginstace axios.interceptors.request.use(config => { // element ui Loading方法 loadinginstace = Loading.service({ fullscreen: true }) return config }, error => { loadinginstace.close() Message.error({ message: '加載超時' }) return Promise.reject(error) }) // http響應攔截器 axios.interceptors.response.use(data => {// 響應成功關閉loading loadinginstace.close() return data }, error => { loadinginstace.close() Message.error({ message: '加載失敗' }) return Promise.reject(error) }) export default axios
如果你是使用了vux,那么在main.js這樣使用:
Vue.prototype.$http.interceptors.response.use()
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創新互聯行業資訊頻道,感謝您對創新互聯的支持。
網頁標題:怎么在vue+axios前端實現攔截
文章轉載:http://m.newbst.com/article6/pjdgog.html
成都網站建設公司_創新互聯,為您提供營銷型網站建設、商城網站、網站策劃、標簽優化、App開發、網站內鏈
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯