nuxt中使用路由守衛的方法步驟


1.在plugins文件下創建一個route.js

import { getCookie, setCookie } from '@/pages/logreg/api/cookie'
import axios from 'axios'
 
export default ({ app, store }) => {
 app.router.beforeEach((to, from, next) => {
  let isClient = process.client
  if (isClient) {
   let currentUrl = location.href
   if (currentUrl.indexOf('access_token=') !== -1) {
    let wechattoken = currentUrl.split('access_token=')[1]
    wechattoken = wechattoken.split('&')[0]
    setCookie('token', wechattoken, 5)
   }
   let token = getCookie('token')
   if (token) {
    store.state.user.userinfo.token = token
    axios
     .get('https://api.ass.net/pub/api/user_info', {
      params: {
       token
      }
     })
     .then(res => {
      res = res.data
      if (res.code == 0) {
       res = res.data
       res.headImg = res.headImg.replace('http:', 'https:')
       store.state.user.userinfo = Object.assign(
        {},
        store.state.user.userinfo,
        res
       )
      }
     })
     .catch(error => console.log(error))
   }
  }
  next()
 })
}

 

2.在nuxt.config.js里面配置

plugins: [
 { src: '@/plugins/route', ssr: true }
],

PS:Nuxt在axios請求攔截中使用路由

最近在開發一個網站,用的nuxt搭建的框架,因為需要在請求token過期之后提示用戶重新登錄並且返回登錄頁面,但是在axios的配置文件中使用router.push一直報錯,都准備放棄使用公眾組件去進行路由跳轉了,但是天無絕人之路,最終在官方文檔中找到了redirect,具體操作如下:

在axios的js文件中添加默認的方法,並且獲取redirect,並且使用使用myredirect將redirect儲存起來

et myredirect;
export default function ({redirect }) {
 myredirect = redirect;
}

 

在需要使用路由跳轉的地方進行跳轉(此處在判斷token過期時跳轉)

if (error.message.toString().slice(-3) === '401') {
  Vue.prototype.$message.error('登陸超時,請重新登陸...')
  setTimeout(function () {
   return myredirect('/login/login')
  }, 2000)
 }

 


免責聲明!

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



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