nuxt 自定義 auth 中間件實現(xiàn)令牌的持久化操作
核心點就是在process.server下,把之前存在 cookie 中的數(shù)據(jù)再用store.commit一下
auth.js
/* eslint-disable no-unused-vars */
/* eslint-disable no-useless-return */
export const TokenKey = 'Admin-token'
/**
* 解析服務(wù)端拿到的cookie
* @param {*} cookie
* @param {*} key
*/
export function getCookie(cookie, key) {
if (!cookie) return
const arrstr = cookie.split('; ')
for (let i = 0; i < arrstr.length; i++) {
const temp = arrstr[i].split('=')
if (temp[0] === key) return unescape(temp[1])
}
}
// 登錄頁
const loginPath = '/login'
// 首頁
const indexPath = '/home'
// 路由白名單,直接繞過路由守衛(wèi)
const whiteList = [loginPath]
/**
* @description 鑒權(quán)中間件,用于校驗登陸
*
*/
export default async ({ store, redirect, env, route, req }) => {
const { path, fullPath, query } = route
const { redirect: redirectPath } = query
// 應(yīng)對刷新 vuex狀態(tài)丟失的解決方案
if (process.server) {
const cookie = req.headers.cookie
const token = getCookie(cookie, TokenKey)
// 設(shè)置登錄狀態(tài)
if (token) {
store.commit('LOGIN', token) //'LOGIN' 和store中的mutations對應(yīng)起來就可以了
}
if (token) {
// 已經(jīng)登錄,進來的是登錄頁,且有重定向的路徑,直接調(diào)跳到重定向的路徑
if (path === loginPath && path !== redirectPath) {
redirect(redirectPath)
} else if (path === '/') {
redirect(indexPath)
} else {
// 其他的已經(jīng)登錄過得直接跳過
return
}
} else {
// 鑒權(quán)白名單
if (whiteList.includes(path)) return
// 未登錄,進來的不是是登錄頁,全部重定向到登錄頁
if (!path.includes(loginPath)) {
redirect(`${loginPath}?redirect=${encodeURIComponent(fullPath)}`)
}
}
}
}
補充知識:NUXT 中間件 Middleware
中間件可以使您的自定義的函數(shù)在渲染頁面之前運行
所有的中間件都必須放置在middleware/目錄下。文件名將作為中間件的名稱(如:middleware/auth將成為中間件auth)。
中間件收到上下文作為第一個參數(shù):
export default function (context) {
context.userAgent = context.isServer ? context.req.headers['user-agent'] : navigator.userAgent
}
中間件將按照此順序在序列中執(zhí)行:
1、nuxt.config.js
2、匹配的布局
3、匹配的頁面
中間件可以是異步的,僅返回一個Promise或者使用第二個callback返回值:
middleware/stats.js
import axios from 'axios'
export default function ({ route }) {
return axios.post('http://my-stats-api.com', {
url: route.fullPath
})
}
然后,在nuxt.config.js,布局或者頁面中,配置middleware參數(shù)
nuxt.config.js
module.exports = {
router: {
middleware: 'stats'
}
}
中間件stats將在每次路由改變時被調(diào)用。
想了解中間件的例子,請移步example-auth0
以上這篇nuxt 自定義 auth 中間件實現(xiàn)令牌的持久化操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
示例vue 的keep-alive緩存功能的實現(xiàn)
這篇文章主要介紹了示例vue 的keep-alive緩存功能的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12
vue element中axios下載文件(后端Python)
這篇文章主要介紹了vue element中axios下載文件(后端Python)的實例代碼,非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-05-05

