nuxt 路由验证几种方式
插件的方式,client模式(错误方法)
route
虽然可以拿到meta,但是在开发的时候按下保存,此时浏览器在哪个页面那么此route
对象就是哪个路由对象,构建的时候确定了哪个路由对象就是哪个路由对象,所以在页面发生跳转后不会进行更新,此处不跟路由中间件一样要从to
对象拿到要进入的对象 to
对象拿不到meta
在client
模式下,可以拿到token
import cookie from '~/utils/cookie'
import globalVar from '~/config/globalVar'
export default ( { app: { router } , route, store, redirect } ) => {
router. beforeEach ( ( to, from , next) => {
const routerItem = route. meta. find ( ( item) => {
return 'requiresAuth' in item && item. requiresAuth
} )
console. log ( route, routerItem, to)
if ( routerItem) {
const token = cookie. get ( globalVar. WEB_TOKEN )
if ( token) {
next ( )
} else {
next ( )
console. log ( 1 )
}
} else {
next ( )
}
} )
}
插件的方式,client模式,列出要验证的路由(正确方法,兼容SSR和静态渲染)
在client
模式下拿到token
在to
对象拿到要进入的路由 通过authRoutes
定义要验证的路由
import cookie from '~/utils/cookie'
import globalVar from '~/config/globalVar'
import { platformURL } from '~/config/index'
export default ( { app: { router } , redirect } ) => {
router. beforeEach ( ( to, from , next) => {
console. log ( 'to' , to)
const authRoutes = [
'/resource-search'
]
const isAuth = authRoutes. includes ( to. path)
if ( isAuth) {
const token = cookie. get ( globalVar. WEB_TOKEN )
if ( token) {
next ( )
} else {
redirect ( platformURL)
}
} else {
next ( )
}
} )
}
路由中间件方式配合store,只适用于SSR模式,不适用于静态渲染
在nuxtServerInit
此内置方法 中,因为是SSR
,所以拿的到req
,通过req
拿到cookie
,判断本地是否登录,如果登录了则设置store
中的state
中的isLogin
状态
import globalVar from '~/config/globalVar'
const cookieparser = process. server ? require ( 'cookieparser' ) : undefined
export const state = ( ) => ( {
isLogin: false ,
} )
export const mutations = {
setIsLogin ( state, data) {
state. isLogin = data
}
}
export const actions = {
nuxtServerInit ( { commit } , { req } ) {
let isLogin = false
if ( req. headers. cookie) {
const parsed = cookieparser. parse ( req. headers. cookie)
console. log ( parsed)
isLogin = parsed[ globalVar. WEB_TOKEN ] ? parsed[ globalVar. WEB_TOKEN ] : false
}
commit ( 'setIsLogin' , isLogin)
}
}
在ssr
模式下,可以在中间件中拿到变化过的store.state
,此时就可以直接判断是否登录,因为在上异步已经通过req.headers.cookie
检查过是否存在token
通过当前route
拿到此路由的meta
,如果meta
存在属性requiresAuth
并且其属性值为true
则表示此路由需要被验证,nuxt
如何设置meta
查看https://github.com/nuxt/nuxt.js/tree/2.x/examples/routes-meta 如果验证失败则通过redirect
方法跳转登录界面
import { platformURL } from '~/config/index'
export default ( { route, store, redirect } ) => {
const isRequiresAuth = route. meta. find ( ( item) => {
return 'requiresAuth' in item && item. requiresAuth
} )
if ( isRequiresAuth) {
if ( ! store. state. isLogin) {
redirect ( platformURL)
}
}
}