【轉】vue+axios 前端實現登入攔截(路由攔截、http攔截)

來源:互聯網
上載者:User

標籤:結合   知識庫   依賴   err   demo   store   ext   使用者訪問   meta   

 一、路由攔截登入攔截邏輯第一步:路由攔截

首先在定義路由的時候就需要多添加一個自訂欄位requireAuth,用於判斷該路由的訪問是否需要登入。如果使用者已經登入,則順利進入路由, 
否則就進入登入頁面。

?
1234567891011121314151617181920 const routes = [    {        path: ‘/‘,        name: ‘/‘,        component: Index    },    {        path: ‘/repository‘,        name: ‘repository‘,        meta: {            requireAuth: true// 添加該欄位,表示進入這個路由是需要登入的        },        component: Repository    },    {        path: ‘/login‘,        name: ‘login‘,        component: Login    }];

定義完路由後,我們主要是利用vue-router提供的鉤子函數beforeEach()對路由進行判斷。

?
12345678910111213141516 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();    }})

  

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

確保要調用 next 方法,否則鉤子就不會被 resolved。

完整的方法見/src/router.js

其中,to.meta中是我們自訂的資料,其中就包括我們剛剛定義的requireAuth欄位。通過這個欄位來判斷該路由是否需要登入許可權。需要的話,同時當前應用不存在token,則跳轉到登入頁面,進行登入。登入成功後跳轉到目標路由。

登入攔截到這裡就結束了嗎?並沒有。這種方式只是簡單的前端路由控制,並不能真正阻止使用者訪問需要登入許可權的路由。還有一種情況便是:當前token失效了,但是token依然儲存在本地。這時候你去訪問需要登入許可權的路由時,實際上應該讓使用者重新登入。 
這時候就需要結合 http 攔截器 + 後端介面返回的http 狀態代碼來判斷。

第二步:攔截器

要想統一處理所有http請求和響應,就得用上 axios 的攔截器。通過配置http response inteceptor,當後端介面返回401 Unauthorized(未授權),讓使用者重新登入。

?
12345678910111213141516171819202122232425262728293031 // 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請求和響應時我們通過設定攔截器處理方便很多.

這個項目我引入了element ui架構,所以我是結合element中loading和message組件來處理的.我們可以單獨建立一個http的js檔案處理axios,再到main.js中引入.

12345678910111213141516171819202122232425262728293031323334 /** * http配置 */// 引入axios以及element ui中的loading和message組件import axios from ‘axios‘import { Loading, Message } from ‘element-ui‘// 逾時時間axios.defaults.timeout = 5000// http請求攔截器var loadinginstaceaxios.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

這樣我們就統一處理了http請求和響應的攔截.當然我們可以根據具體的業務要求更改攔截中的處理.

 

vue2+element更全面,更簡單深入的例子 請查看:https://github.com/guo11111/vue2-demo

轉自:https://www.cnblogs.com/guoxianglei/p/7084506.html

【轉】vue+axios 前端實現登入攔截(路由攔截、http攔截)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.