前提参考:vue项目封装axios
思路:
// 1, 前端校验,校验成功后向后台传用户名和密码(每次请求接口都要传 token)
// 2, 后端收到请求,验证用户名和密码,验证成功,生成 token 返回给前端
// 3, 前端拿到token,将token存储到sessionStorage
// 4, 跳转路由,就判断 localStroage 中有无 token ,没有就跳转到登录页面,有则跳转到对应路由页面
// 5, 后端判断请求头中有无token,有token,就拿到token并验证token,验证成功就返回数据,验证失败(例如:token过期)就返回401,请求头中没有token也返回401
// 6, 如果前端拿到状态码为401/退出登录,就清除token信息并跳转到登录页面
request.js
//http request 拦截器
instance.interceptors.request.use(config => {let token = sessionStorage.getItem('token')if(token == null){// 首次登录config.headers.client_id = 'jeecp'config.headers.client_secret = 'webApp'}else{config.headers.Authorization = 'Bearer '+ token}return config},err => {return Promise.reject(err)}
)
api.js
// 登录loginInfor(Information){return post('/api-auth/oauth/user/token' ,{username: Information.username,password: Information.password,})},
登录前端页面
<template><el-container id="login"><el-aside width="70%"><p class="welcome">智能环境照明子系统欢迎您</p></el-aside><el-main><p>智能环境照明子系统</p><el-form ref="Form" :model="loginForms" :rules="loginRules" label-width="80px"><el-form-item prop="username"><el-input v-model="loginForms.username"><template slot="prepend"><i class="el-icon-user"></i></template></el-input></el-form-item><el-form-item prop="password"><el-input v-model="loginForms.password"><template slot="prepend"><i class="el-icon-goods"></i></template></el-input></el-form-item><el-button round @click.native.prevent="submit">登陆</el-button></el-form></el-main></el-container>
</template>
<style scoped>
#login{width: 100%;height: 100%;
}#login .el-aside{height: 100%;background-image: url('~@/assets/img/login_bg.png');position: relative;background-size: 100% 100%;background-repeat: no-repeat;
}
#login .el-aside .welcome{text-align: center;margin: 0 auto;position: absolute;top: 50%;transform: translateY(-50%);left: 49%;transform: translateX(-50%);font-size: 40px;color: #fff;
}
#login .el-main{padding: 0;background-color: rgba(77, 120, 223, 1);
}
#login .el-main p{color: #fff;font-size: 30px;margin-top: 45%;margin-bottom: 10%;
}#login .el-main .el-input-group{width: 70%;/* margin: 0 15% 30px 15%; */
}
#login .el-main .el-button{width: 35%;color: rgba(77, 120, 223, 1);
}
@media screen and (min-width: 1600px) and (max-width: 1920px) {#login .el-main p{margin-top: 67%;}
}
@media screen and (min-width: 1400px) and (max-width: 1600px) {#login .el-main p{margin-top: 65%;}
}
</style>
<style>
*{padding: 0;margin: 0;
}
</style>
<script>
import $ from "jquery"
export default {data (){return {loginForms:{username: 'fox',password: '123456'},loginRules: {username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],password: [{ required: true, trigger: 'blur', message: '密码不能为空' }]}}},mounted() {$('#app').height($(window).height())$('.el-form-item__content').css("margin-left", "0")},methods: {// 重置登录表单resetLoginForm() {this.$refs.Form.resetFields()},// 登录submit(){this.$router.push("/index");// 测试表单数据校验 Form 要和 表单的ref的名称一致this.$refs.Form.validate(valid => {// console.log('校验结果: ' + valid)if (!valid) {console.log("参数验证失败")return}// 校验成功this.$api.loginInfor(this.loginForms).then(res => {// console.log('请求结果:', res)if (res.code !== '000000') {// console.log("登录失败")return}else{console.log("token", res.data.access_token)// token放入 sessionStoragewindow.sessionStorage.setItem('token', res.data.access_token)// 跳转到首页this.$router.push({path: "/index"});}}).catch(err => {console.log(err)})})}}
}
</script>
路由 index.js
// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
router.beforeEach((to, from, next) => {// to 将要访问的路径// from 从哪里跳转来// next 放行//跳转到登录页面直接放行if (to.path === '/login') {next();} else {// 获取token,看是否有token,有token放行const token = window.sessionStorage.getItem("token")if (!token) {next('/login')return;} else{// 放行next();}}
});