前端攔截

(路由攔截)

// 首先在定義路由的時候就須要多添加一個自定義字段requireAuth,用於判斷該路由的訪問是否須要登陸。若是用戶已經登陸,則順利進入路由, 
const routes = [
    {
        path: '/',
        name: '/',
        component: Index
    },
    {
        path: '/repository',
        name: 'repository',
        meta: {
            requireAuth: true,  // 添加該字段,表示進入這個路由是須要登陸的
        },
        component: Repository
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    }
];
複製代碼
///咱們主要是利用vue-router提供的鉤子函數beforeEach()對路由進行判斷 
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();
    }
})

*注意:vue與react均可以使用
// 每一個鉤子方法接收三個參數: 
// * to: Route: 即將要進入的目標 路由對象 
// * from: Route: 當前導航正要離開的路由 
// * next: Function: 必定要調用該方法來 resolve 這個鉤子。執行效果依賴 next 方法的調用參數。 
// * next(): 進行管道中的下一個鉤子。若是所有鉤子執行完了,則導航的狀態就是 confirmed (確認的)。 
// * next(false): 中斷當前的導航。若是瀏覽器的 URL 改變了(多是用戶手動或者瀏覽器後退按鈕),那麼 URL 地址會重置到 from 路由對應的地址。
// * next(‘/’) 或者 next({ path: ‘/’ }): 跳轉到一個不一樣的地址。當前的導航被中斷,而後進行一個新的導航。
複製代碼

攔截器

// 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攔截

/** * 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方法F
 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
複製代碼
相關文章
相關標籤/搜索