token一種身份的驗證,在大多數網站中,登錄的時候都會攜帶token,去訪問其他頁面,token就想當於一種令牌。可以判斷用戶是否登錄狀態。本次頁面是通過Element-ui搭建的登錄界面

當用戶登錄的時候,向后端發起請求的時候,后端會返回給我一個token,前端可以進行校驗,進行處理token

當前端拿到后端返回的token,可以通過localStorage存儲到本地,然后通過jwt-decode對token進行解析,jwt-decode是一種對token的解析包,通過npm install jwt-decode

設置好存儲方式后,當用戶再次登錄的時候,在瀏覽器段可以看點用戶存儲的token。

當頁面很多地方需要用到token的時候,用戶必須攜帶token才能訪問其他頁面,可以通過請求攔截和響應攔截設置,並且在響應攔截的時候處理token是否過時,過期時間是通過后端設置的,前端需要判斷token的狀態碼是否過時就行
import axios from 'axios'
import { Loading ,Message} from 'element-ui' //引入了element-ui框架庫
import router from './router/index.js'
let loading;
function startLoading() {
loading =Loading.service({
lock: true,
text: '加載中...',
background: 'rgba(0, 0, 0, 0.7)'
});
}
function endLoading() {
loading.close()
}
// 請求攔截
axios.interceptors.request.use(config => {
startLoading()
//設置請求頭
if(localStorage.eleToken) {
config.headers.Authorization = localStorage.eleToken
}
return config
}, error => {
return Promise.reject(error)
})
// 響應攔截
axios.interceptors.response.use(response => {
endLoading()
return response
}, error => {
Message.error(error.response.data)
endLoading();
//獲取狀態碼
const {status} = error.response;
if(status === 401) {
Message.error("token失效,請重新登錄");
//清除token
localStorage.removeItem('eleToken');
//重新登錄
router.push('/login')
}
return Promise.reject(error)
})
export default axios;
存儲vuex
如果頁面過多,不想數據來回傳遞,這時候就可以用到vuex來存儲數據了,這樣每個頁面都可以通過store獲取用戶信息了。當用戶拿到token令牌的時候,會得到用戶的信息,
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const type = {
SET_AUTHORIZATION:"set_authorization",
SET_USER:"set_user"
}
const state = {
isAuthorization:false,
user:{}
}
const getters = { //獲取state狀態
isAuthorization: state => state.isAuthorization,
user: user => state.user
}
const mutations= {
[type.SET_AUTHORIZATION](state,isAuthorization){
if(isAuthorization){
state.isAuthorization = isAuthorization
} else {
isAuthorization = false
}
},
[type.SET_USER](state,user) {
if(user) {
state.user = user
} else {
user={}
}
}
}
const actions = {
setAuthorization:({commit},isAuthorization) => {
commit(type.SET_AUTHORIZATION,isAuthorization)
},
setsuer:({commit},user) => {
commit(type.SET_USER,user)
}
}
export const store = new Vuex.Store({
state,
getters,
mutations,
actions
})
通過以上vuex設置,我們可以吧得到的token和用戶的一些信息存儲到vuex中,方便其他頁面進行調用
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
this.$axios.post('/api/users/login',this.loginUser).then(res => {
const {token} = res.data;
//存儲token
localStorage.setItem('eleToken',token)
//解析token
const decode = jwt_decode(token)
console.log(res)
// 存儲到vuex
this.$store.dispatch("setAuthorization", !this.isEmpty(decode));
this.$store.dispatch("setsuer",decode)
// this.$router.push('/index')
})
}
})
},
//封裝的驗證方法
isEmpty(value) {
return (
value === undefined ||
value === null ||
(typeof value === "object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0)
);
}
雖然token和用戶信息存儲到vuex中了,當我們刷新瀏覽器的時候,存儲的vuex數據都沒有了,
這時候。我們需要在跟組件app.vue組件進行判斷,token是否存在本地,存在就存放到vuex中
export default {
name: 'App',
created(){
if(localStorage.setItem) {
const decode = jwt_decode(localStorage.eleToken)
// 存儲到vuex
this.$store.dispatch("setAuthorization", !this.isEmpty(decode));
this.$store.dispatch("setsuer",decode)
}
},
methods:{
isEmpty(value) {
return (
value === undefined ||
value === null ||
(typeof value === "object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0)
);
}
}
}
路由守衛
路由跳轉前做一些驗證,比如登錄驗證,購物車,是網站中的普遍需求,在用戶沒有登錄的狀態下,是無法訪問其他頁面的,這是時候我們就可以通過beforeEach來判斷用戶是否登錄,(原理不需要細講,官方文檔有,直接上代碼),還是直接通過token去驗證是否登錄或者沒有登錄狀態
router.beforeEach((to,from,next) => {
const isLogin = localStorage.eleToken ? true : false
if(to.path === '/login' || to.path === 'register') {
next()
} else {
isLogin ? next() : next('/login')
}
})
以上都是這次博客中所有的內容,如果喜歡,可以關注一下!!!
