登录
Vue项目中实现登录功能:
- 第一次登录的时候,前端调后端的登陆接口,发送用户名和密码
- 后端收到请求,验证用户名和密码,验证成功,就给前端返回一个token
- 前端拿到token,将token存储到localStorage和vuex中,并跳转路由页面
- 前端每次跳转路由,就判断 localStroage 中有无 token ,没有就跳转到登录页面,有则跳转到对应路由页面
- 每次调后端接口,都要在请求头中加token
- 后端判断请求头中有无token,有token,就拿到token并验证token,验证成功就返回数据,验证失败(例如:token过期)就返回401,请求头中没有token也返回401
- 如果前端拿到状态码为401,就清除token信息并跳转到登录页面
- 调取登录接口成功,会在回调函数中将token存储到localStorage和vuex中
登录页面
<template>
<div class="lcCon">
<div class="lccTitle">xx管理平台</div>
<div class="lccCon">
<div class="lcccItem">
<img src="../../../static/images/login/icon_username.png" />
<input
type="text"
v-model="loginForm.username"
placeholder="请输入账号"
/>
</div>
<div class="lcccItem">
<img src="../../../static/images/login/icon_password.png" />
<input
type="password"
v-model="loginForm.password"
placeholder="请输入密码"
/>
</div>
</div>
<div class="lccHint">
<p class="left">
<img src="../../../static/images/login/icon-duox-2.png" />
<span>记住密码</span>
</p>
<p class="right" v-on:click="showFindPwd">忘记密码</p>
</div>
<div class="lccBtn" v-on:click="handleLogin">立即登录</div>
<div class="lccTxt" v-on:click="showRegister">账号注册</div>
</div>
</template>
<script>
import loginHttps from "@/https/login/login";
export default {
name: "",
data() {
return {
loginForm: {
username: "",
password: "",
},
};
},
created() {},
computed: {},
methods: {
//登录
handleLogin() {
let that = this;
if (this.loginForm.username === "" || this.loginForm.password === "") {
return alert("账号或密码不能为空");
} else {
loginHttps
.login(that.loginForm)
.then(function (res) {
if (res.data.code == 200) {
let userInfo = res.data.data.user;
let token = "Beare " + res.data.data.token;
localStorage.setItem("userInfo", JSON.stringify(userInfo));
localStorage.setItem("token", token);
}
})
.catch((error) => {
alert("账号或密码错误");
console.log(error);
});
}
},
},
};
</script>
<style lang='scss' scoped>
</style>
导航守卫
router文件夹下的index.js
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "index",
component: () => import("../views/index/index.vue"),
},
{
path: "/login",
component: () => import("../views/login/login.vue"),
},
];
const router = new VueRouter({
routes,
});
// 使用 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;
请求拦截器
/****** request拦截器==>对请求参数做处理 ******/
service.interceptors.request.use(config => {
showLoading();
let token = localStorage.getItem("token");
config.headers.Authorization = token;
return config;
}, error => { //请求错误处理
console.log(error);
Promise.reject(error);
});