vue项目实现登录携带token
Posted huanhuan55
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue项目实现登录携带token相关的知识,希望对你有一定的参考价值。
1.用户第一次登录,调用后端登录接口,发送用户名和密码
2.后端验证用户名和密码是否正确,成功则返回token,
3.前端拿到token,将token存储在localStorge()和vuex中,并跳转到主页
4.前端每次跳转路由就判断localStorge中是否有token,没有就跳转到登录页
5.每次调用后端,都要在请求头部添加token
6.后端判断是否有token,有token,就验证token,验证成功就返回数据,验证失败,token过期,或没有就返回401
7.前端如果,拿到401就清除token并跳转到登录页,
<template>
<div>
<input type="text" v-model="loginForm.username" placeholder="用户名"/>
<input type="text" v-model="loginForm.password" placeholder="密码"/>
<button @click="login">登录</button>
</div>
</template>
export default {
data () {
return {
loginForm: {
username: ‘‘,
password: ‘‘ }
};
},
methods: {
...mapMutations([‘changeLogin‘]),
login () {
let _this =this;
/////判读账号密码是否输入,没有则alert 出来
if(this.loginForm.username === ‘‘ ||this.loginForm.password === ‘‘) {
alert(‘账号或密码不能为空‘);
} else {
this.axios({
method: ‘post‘,
url: ‘/user/login‘,
data: _this.loginForm
}).then(res => {
console.log(res.data);
_this.userToken = ‘Bearer ‘ + res.data.data.body.token;
// 将用户token保存到vuex中 _this.changeLogin({ Authorization: _this.userToken });
_this.$router.push(‘/home‘);
alert(‘登陆成功‘);
}).catch(error => {
alert(‘账号或密码错误‘);
console.log(error);
});
}
}
}
};
在store文件夹下的index.js 添加 token import Vue from ‘vue‘; import Vuex from ‘vuex‘; Vue.use(Vuex); const store = new Vuex.Store({ state: { // 存储token Authorization: localStorage.getItem(‘Authorization‘) ? localStorage.getItem(‘Authorization‘) : ‘‘ }, mutations: { // 修改token,并将token存入localStorage changeLogin (state, user) { state.Authorization = user.Authorization; localStorage.setItem(‘Authorization‘, user.Authorization); } } }); export default store;
配置路由导航守卫 router文件夹下的index.js import Vue from ‘vue‘; import Router from ‘vue-router‘; import login from ‘@/components/login‘; import home from ‘@/components/home‘; Vue.use(Router); const router = new Router({ routes: [ { path: ‘/‘, redirect: ‘/login‘ }, { path: ‘/login‘, name: ‘login‘, component: login }, { path: ‘/home‘, name: ‘home‘, component: home } ] }); // 导航守卫 // 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆 router.beforeEach((to, from, next) => { if (to.path === ‘/login‘) { next(); } else { let token = localStorage.getItem(‘Authorization‘); if (token === ‘null‘ || token === ‘‘) { next(‘/login‘); } else { next(); } } }); export default router;
请求头加token 在 main.js中添加 // 添加请求拦截器,在请求头中加token axios.interceptors.request.use( config => { if (localStorage.getItem(‘Authorization‘)) { config.headers.Authorization = localStorage.getItem(‘Authorization‘); } return config; }, error => { return Promise.reject(error); });
如果前端拿到状态码为401,就清除token信息并跳转到登录页面 localStorage.removeItem(‘Authorization‘); this.$router.push(‘/login‘); 链接:https://www.jianshu.com/p/32e6eb23147f
以上是关于vue项目实现登录携带token的主要内容,如果未能解决你的问题,请参考以下文章