Nuxt用户登录路由鉴权

在使用Nuxt.js框架中 无法像Vue中使用sessionStorage,LocalStorage将数据存储在本地。无法存储在本地就失去判断用户是否登录的条件,有什么办法能够判断用户是否登录了呢?

一. 安装需要的依赖

npm install js-cookie --save

二. 在登录页面 Login

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    import Cookie from 'js-cookie'
data() {
return {
redirectURL:'/'
}
},
mounted() {
// 初始化路由
let rediretUrl = this.$route.query.ref
if (rediretUrl) {
this.redirectURL = rediretUrl
}
},
methods:{
// 登录的方法
handleLogin() {
post(login, { phone: 15555429216, password: 123456 })
.then(res => {
if (res.status === 200) {
Cookie.set('token',res.token)
this.$router.push('/afterLogin')
}
})
.catch(error => {
console.log(error)
})
}
}
},

三. 添加权限中间件 与 需求文件

  1. 在middleware中新增auth.js文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    import utils from '../utils/utils'
    export default function ({ route, req, res, redirect }) {
    let isClient = process.client;
    let isServer = process.server;
    let redirectURL = '/login';
    var token, path
    // console.log(req);
    // console.log(isClient,isServer);
    //在服务端
    if (isServer) {
    let cookies = utils.getcookiesInServer(req)
    path = req.originalUrl;
    token = cookies.token || ''
    }
    //在客户端判读是否需要登陆
    if (isClient) {
    token = utils.getcookiesInClient('token')
    path = route.path;
    }
    if (path) {
    redirectURL = '/login?ref=' + encodeURIComponent(path)
    }
    //需要进行权限判断的页面开头
    if (!token) {
    redirect(redirectURL)
    }
    }
  2. utils方法 在根目录添加新增 utils/utils.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import Cookie from 'js-cookie'
    export default {
    //获取服务端cookie
    getcookiesInServer:function (req) {
    let service_cookie = {};
    req && req.headers.cookie && req.headers.cookie.split(';').forEach(function (val) {
    let parts = val.split('=');
    service_cookie[parts[0].trim()] = (parts[1] || '').trim();
    });
    return service_cookie;
    },
    //获取客户端cookie
    getcookiesInClient: function (key) {
    console.log(key);
    return Cookie.get(key) ? Cookie.get(key) : ''
    }
    }

四. 如何使用

  1. 在需要的权限的页面添加
    1
    middleware: 'auth'

参考:https://blog.csdn.net/umufeng/article/details/80524766