vue+axios 前端實現的常用攔截


一、路由攔截使用

首先在定義路由的時候就需要多添加一個自定義字段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();
    }
})

二、攔截器使用

要想統一處理所有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解決跨域問題和攔截器使用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM