文件設置參考地址:https://gitee.com/wang_yu5201314/headlines__news/tree/master/%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E6%96%87%E4%BB%B6/src
文件夾 Router 文件夾 index.js 中設置 全局導航守衛
文件 mian.js 中設置 請求、響應攔截器
設置 請求、響應攔截器
// ************************* axios **************************************
import axios from 'axios'axios.defaults.baseURL = 'http://localhost:3000'
Vue.prototype.$axios = axios
// 請求攔截器
axios.interceptors.request.use(config => {// 攔截請求 , 給每個需要token請求的地方添加tokenlet token = localStorage.getItem('token')if (token) {config.headers.Authorization = token}return config
})
// 響應攔截器
axios.interceptors.response.use(res => {// console.log('響應被截胡了', res)const { message, statusCode } = res.dataif (message === '用戶信息驗證失敗' && statusCode === 401) {// 1. 提示Toast.fail('token失效')// 2. 刪除本地token 和 user_idlocalStorage.removeItem('token')localStorage.removeItem('user_id')// 3. 跳轉 login// router.push('/login')router.push({name: 'login',params: {back: true,},})}return res
})
VUE全局導航守衛
// 全局導航守衛
// 說明 : 只要路由改變了就會走導航守衛 ( /login => /user )
// to : 將要訪問哪里 ($route路由對象 to.path) ★
// from : 從哪里來 ($route路由對象 from.path)
// next : 是否放行
// next() => 直接放行 ★
// next(false) => 不放行
// next('/login') => 像重定向 => 放行 => 去 /login ★
router.beforeEach((to, from, next) => {// console.log('to', to.path)let token = localStorage.getItem('token')// 把需要攔截未登錄訪問的權限頁面 全部都加到數組里面let autlUrlArr = ['/user', '/myfollow', '/mycomments', '/mystar']// 如果訪問的是 /user => 繼續判斷// if(to.path === '/user' || to.path)// if (autlUrlArr.indexOf(to.path) > -1) {if (autlUrlArr.includes(to.path)) {// 如果登錄了 可以訪問if (token) {next()} else {// 如果沒有登錄 跳轉到登錄頁面next('/login')}} else {// 如果訪問的是 /login /register => 永遠可以next()}
})