nuxtjs之前端持久登录态

nuxtjs是一个服务端渲染的框架,它的生命周期中有仅在服务端执行的,有仅在客户端执行的,有服务端和客户端执行的。

我们在保存登录态token到缓存中的时候,如果页面不刷新跳转,则钩子方法在客户端执行,token则在document对象上;如果页面刷新,则钩子方法执行在服务端,token则在请求头中。

解决这两种情况的兼容:

1、在封装axios的时候,在请求回调中判断window对象是否存在,拿到token然后再放请求头中。

  // 请求回调
  $axios.onRequest(config => {
    if (!config.headers.token) {
      let decodedCookie = decodeURIComponent(typeof window === "undefined" ? req.headers.cookie : document.cookie);
      config.headers.token = common.getCookie(decodedCookie, ‘token‘)
    }
  })

2、在需要进行页面权限需要token验证的时候,则需要在middleware文件夹下新建一个auth.js文件来来检验。

export default async function ({ route, req, $axios, redirect, common }) {
  let isAdmin = /^\/admin/ig.test(route.path)

  if (isAdmin) {
    let decodedCookie = decodeURIComponent(typeof window === "undefined" ? req.headers.cookie : document.cookie);
    let token = common.getCookie(decodedCookie, ‘token‘)

    if (token) {
      $axios.defaults.headers[‘token‘] = token
    
      let res = await $axios.post(‘/server/verifyToken‘)
      if (res.errcode !== 0) {
        redirect(‘/login‘)
      }
    } else {
      redirect(‘/login‘)
    }
  }
}

然后在nuxt.config.js中修改:

  plugins: [
      src: "@/plugins/axios"
    }
  ],
  modules: [
    ‘@nuxtjs/axios‘
  ],
  router: {
    middleware: ‘auth‘,
    scrollBehavior(to, from, savedPosition) {
      return { x: 0, y: 0 }
    }
  }

 

nuxtjs之前端持久登录态

上一篇:编写php自定义扩展


下一篇:前端实现浏览器端大文件分片上传