核心点就是在process.server下,把之前存在 cookie 中的数据再用store.commit一下
auth.js
/* eslint-disable no-unused-vars */ /* eslint-disable no-useless-return */ export const TokenKey = 'Admin-token' /** * 解析服务端拿到的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' // 路由白名单,直接绕过路由守卫 const whiteList = [loginPath] /** * @description 鉴权中间件,用于校验登陆 * */ export default async ({ store, redirect, env, route, req }) => { const { path, fullPath, query } = route const { redirect: redirectPath } = query // 应对刷新 vuex状态丢失的解决方案 if (process.server) { const cookie = req.headers.cookie const token = getCookie(cookie, TokenKey) // 设置登录状态 if (token) { store.commit('LOGIN', token) //'LOGIN' 和store中的mutations对应起来就可以了 } if (token) { // 已经登录,进来的是登录页,且有重定向的路径,直接调跳到重定向的路径 if (path === loginPath && path !== redirectPath) { redirect(redirectPath) } else if (path === '/') { redirect(indexPath) } else { // 其他的已经登录过得直接跳过 return } } else { // 鉴权白名单 if (whiteList.includes(path)) return // 未登录,进来的不是是登录页,全部重定向到登录页 if (!path.includes(loginPath)) { redirect(`${loginPath}"color: #ff0000">补充知识:NUXT 中间件 Middleware中间件可以使您的自定义的函数在渲染页面之前运行
所有的中间件都必须放置在middleware/目录下。文件名将作为中间件的名称(如:middleware/auth将成为中间件auth)。
中间件收到上下文作为第一个参数:
export default function (context) { context.userAgent = context.isServer "htmlcode">import axios from 'axios' export default function ({ route }) { return axios.post('http://my-stats-api.com', { url: route.fullPath }) }然后,在nuxt.config.js,布局或者页面中,配置middleware参数
nuxt.config.js
module.exports = { router: { middleware: 'stats' } }中间件stats将在每次路由改变时被调用。
想了解中间件的例子,请移步example-auth0
以上这篇nuxt 自定义 auth 中间件实现令牌的持久化操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]
- 曼丽2021《女人三十2雾之恋》HQCD[WAV+CUE]
- 隔壁老樊.2019-我曾【好听音乐】【FLAC分轨】
- 高林生.1993-牵挂你的人是我【白天鹅】【WAV+CUE】
- 洪卓立.2012-找个懂我的女孩(国专)【英皇娱乐】【WAV+CUE】
- 曼丽2022《女人三十3晚秋》HQCD[WAV+CUE]
- 曼丽2018《女人三十4冬天》HQCD[WAV+CUE]
- 柏菲-《好歌30年壹》限量开盘母带ORMCD[低速原抓WAV+CUE]
- 大自然音乐系列《水舞》[WAV/CUE/分轨][424.3MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]