axios 攔截 , 頁面跳轉, token 驗證


 

第一步: 路由 多添加一個自定義字段 requireAuth

 

 path: '/repository',  name: 'repository',  meta: {  requireAuth: true, // 添加該字段,表示進入這個路由是需要登錄的 },  component: Repository

 

第二步: 

  

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



登錄攔截到這里就結束了嗎?並沒有。

這種方式只是簡單的前端路由控制,並不能真正阻止用戶訪問需要登錄權限的路由。(可手動在瀏覽器地址欄輸入沒有權限的路由)

還有一種情況便是:當前token失效了,但是token依然保存在本地。

這時候你去訪問需要登錄權限的路由時,實際上應該讓用戶重新登錄。

這時候就需要結合 http 攔截器 + 后端接口返回的http 狀態碼來判斷。

 

 

第三步:  攔截器 (要想統一處理所有http請求和響應,就得用上 axios 的攔截器。)

 

每次跳頁面, 都要獲取新路由對應的html頁面, 這時候可以用axios的http攔截

每次路由跳轉, 都先讓后台驗證一下token是否有效, 在http頭添加token, 

當后端接口返回 401 Unauthorized(未授權) ,讓用戶重新登錄。

 

關於Autorization     使用之后會忽略cookie的token,  削弱了安全性, 可以配合https

 

// 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 旌旗 靈醫 , 只用[授權] 旌旗的醫生 才是 靈醫
// 返回 401 清除token信息並跳轉到登錄頁面 store.commit(types.LOGOUT); router.replace({ path: 'login', query: {redirect: router.currentRoute.fullPath} }) } } return Promise.reject(error.response.data) // 返回接口返回的錯誤信息 });

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

 

通過上面這幾步,就可以在前端實現登錄攔截了。 

登出 功能也就很簡單,只需要把當前token清除,再跳轉到首頁即可。

 

 

 

 github

 

后台直接跳轉方法:

 

這種方法只要沒有登錄 或者登錄超時,  

訪問任何頁面都會跳轉到登錄頁面,  

把不需要驗證的頁面也給攔截了

 

 

 

在index.html 加載一個 config.jsp

 

//加載
document.write("<script src='"+(T.cookie.get("path") || "/abc")+"/html5/config.do?sid=" + sid + "'></", "script>");

 

config.jsp

 

<c:when test="${isLogin}">
/*
配置文件
*/
var FileConfig = { ... }

</c:when>
<c:otherwise>
   window.location.href = '/html5/login.do';
</c:otherwise>

一個axios靠譜的封裝


免責聲明!

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



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