vue+axios 前端實現登陸攔截(路由攔截、http攔截)html
1、路由攔截
登陸攔截邏輯
第一步:路由攔截
首先在定義路由的時候就須要多添加一個自定義字段requireAuth,用於判斷該路由的訪問是否須要登陸。若是用戶已經登陸,則順利進入路由,
不然就進入登陸頁面。前端
const routes = [vue
{ path: '/', name: '/', component: Index }, { path: '/repository', name: 'repository', meta: { requireAuth: true, // 添加該字段,表示進入這個路由是須要登陸的 }, component: Repository }, { path: '/login', name: 'login', component: Login }
];
定義完路由後,咱們主要是利用vue-router提供的鉤子函數beforeEach()對路由進行判斷。ios
router.beforeEach((to, from, next) => {vue-router
if (to.meta.requireAuth) { // 判斷該路由是否須要登陸權限 if (store.state.token) { // 經過vuex state獲取當前的token是否存在 next(); } else { next({ path: '/login', query: {redirect: to.fullPath} // 將跳轉的路由path做爲參數,登陸成功後跳轉到該路由 }) } } else { next(); }
})
vuex
每一個鉤子方法接收三個參數:element-ui
確保要調用 next 方法,不然鉤子就不會被 resolved。axios
完整的方法見/src/router.jssegmentfault
其中,to.meta中是咱們自定義的數據,其中就包括咱們剛剛定義的requireAuth字段。經過這個字段來判斷該路由是否須要登陸權限。須要的話,同時當前應用不存在token,則跳轉到登陸頁面,進行登陸。登陸成功後跳轉到目標路由。後端
登陸攔截到這裏就結束了嗎?並無。這種方式只是簡單的前端路由控制,並不能真正阻止用戶訪問須要登陸權限的路由。還有一種狀況即是:當前token失效了,可是token依然保存在本地。這時候你去訪問須要登陸權限的路由時,實際上應該讓用戶從新登陸。
這時候就須要結合 http 攔截器 + 後端接口返回的http 狀態碼來判斷。
第二步:攔截器
要想統一處理全部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) // 返回接口返回的錯誤信息 });
2、http攔截
攔截器
首先咱們要明白設置攔截器的目的是什麼,當咱們須要統一處理http請求和響應時咱們經過設置攔截器處理方便不少.
這個項目我引入了element ui框架,因此我是結合element中loading和message組件來處理的.咱們能夠單獨創建一個http的js文件處理axios,再到main.js中引入.
*/
// 引入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
這樣咱們就統一處理了http請求和響應的攔截.固然咱們能夠根據具體的業務要求更改攔截中的處理.
轉載自:https://www.cnblogs.com/guoxi...
2 vue中axios的使用與封裝
https://segmentfault.com/a/11...