調取登陸接口 (首先明確一下要作到事情)前端
在先後端徹底分離的狀況下,Vue項目中實現token驗證大體思路以下:vue
頁面模板ios
<template>
<div>
<input type="text" v-model="loginForm.username" placeholder="用戶名"/>
<input type="text" v-model="loginForm.password" placeholder="密碼"/>
<button @click="login">登陸</button>
</div>
</template>
複製代碼
邏輯實現vue-router
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);
});
}
},
},
};
複製代碼
3.在store文件夾下的index.js 添加 tokenvuex
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.jsaxios
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
axios.interceptors.request.use( config => {
if (localStorage.getItem('Authorization'))
{
config.headers.Authorization = localStorage.getItem('Authorization');
}
return config; },
error => { return Promise.reject(error);
});
複製代碼
token的過時能夠自定義後端
localStorage.removeItem('Authorization'); this.$router.push('/login');
複製代碼