Vue項(xiàng)目中token驗(yàn)證登錄(前端部分)
本文實(shí)例為大家分享了Vue項(xiàng)目中token驗(yàn)證登錄的具體代碼,供大家參考,具體內(nèi)容如下
1、前言
最近在做畢業(yè)設(shè)計(jì),我是做后端的,前端并不是很懂,看vue這個(gè)框架看了近兩個(gè)禮拜才有點(diǎn)入門的感覺,所以這篇文章寫的可能不怎么好,僅作記錄,有什么不對(duì)或不足的地方歡迎大神指出。
2、問題
做一個(gè)登錄界面,我選擇的是用token進(jìn)行驗(yàn)證登錄,我用的前端框架是Vue.js 和 element-ui,如何在vue 中使用token進(jìn)行驗(yàn)證登錄。
3、思考
1、利用token進(jìn)行驗(yàn)證登錄,用戶進(jìn)行登錄操作時(shí),后臺(tái)會(huì)生成一個(gè)token返回給前端,由前端 將這個(gè)token放到請(qǐng)求頭中(這個(gè)是百度的,一般都是放在請(qǐng)求頭),并且此后調(diào)用接口都要把token放到請(qǐng)求的請(qǐng)求頭傳回給后臺(tái);
2、用戶登錄后,前端需要把token保存下來,后面發(fā)送請(qǐng)求的時(shí)候在拿出來;
3、在發(fā)送每個(gè)請(qǐng)求時(shí)都要把token加到請(qǐng)求頭里,寫一個(gè)全局的攔截器。
4、記錄和說明
1、 在src文件夾(我的vue項(xiàng)目是用vue-cli 腳手架創(chuàng)建的)下創(chuàng)建一個(gè)store文件夾,在store中創(chuàng)建一個(gè)index.js

2、src/store/index.js
import Vue form 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
token: localStorage.getItem('token') ? localStorage.getItem('token') : ''
},
mutotions: {
setToken (state,token) {
state.token =token;
localStorage.setItem("token",token.token);
},
delToken (state) {
state.token = '';
localStorage.removeItem("token");
}
}
})
export default store;
說明:
(1)在寫src/store/index.js 里的內(nèi)容之前,要在你的項(xiàng)目里安裝Vuex ,這里只提供npm的安裝方法,在項(xiàng)目根目錄處打開cmd 輸入下面的命令,后回車
npm install vuex --save
(2) 在這個(gè)store/store/index.js中 這段代碼token.token , 是因?yàn)樵趌ogin.vue中調(diào)用這個(gè)放法傳進(jìn)來的是一個(gè)對(duì)象(即使你覺的你傳進(jìn)來的是一個(gè)字符串,不知道為什么會(huì)被放到object里去),傳進(jìn)來的對(duì)象里有token這個(gè)屬性
localStorage.setItem("token",token.token);
3、src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
import promise from 'es6-promise'
import store from './store/index'
promise.polyfill()
Vue.use(ElementUI)
Vue.config.productionTip = false
axios.defaults.baseURL= 'http://192.168.80.152:8088'
axios.defaults.headers.post['Content-Type'] = "application/json"
axios.defaults.withCredentials = true
axios.defaults.headers.common['Authorization'] = store.state.token
Vue.prototype.$axios = axios
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
});
// 添加請(qǐng)求攔截器
axios.interceptors.request.use(config => {
// 在發(fā)送請(qǐng)求之前做些什么
//判斷是否存在token,如果存在將每個(gè)頁面header都添加token
if(store.state.token){
config.headers.common['Authorization']=store.state.token.token
}
return config;
}, error => {
// 對(duì)請(qǐng)求錯(cuò)誤做些什么
return Promise.reject(error);
});
// http response 攔截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
this.$store.commit('del_token');
router.replace({
path: '/login',
query: {redirect: router.currentRoute.fullPath}//登錄成功后跳入瀏覽的當(dāng)前頁面
})
}
}
return Promise.reject(error.response.data)
});
說明
(1)這個(gè)是全部的代碼,不一定都和這個(gè)一樣,下面說說用token驗(yàn)證,src/main.js中要配置那些東西
(2)
import store from './store/index'
上面的代碼是將之前寫的src/store/index.js導(dǎo)入到main.js中
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
});
上述代碼的store是將store掛載到Vue上,后面可以用this.$store 來獲取store
(3)
// 添加請(qǐng)求攔截器
axios.interceptors.request.use(config => {
// 在發(fā)送請(qǐng)求之前做些什么
//判斷是否存在token,如果存在將每個(gè)頁面header都添加token
if(store.state.token){
config.headers.common['Authorization']=store.state.token.token
}
return config;
}, error => {
// 對(duì)請(qǐng)求錯(cuò)誤做些什么
return Promise.reject(error);
});
// http response 攔截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
this.$store.commit('del_token');
router.replace({
path: '/login',
query: {redirect: router.currentRoute.fullPath}//登錄成功后跳入瀏覽的當(dāng)前頁面
})
}
}
return Promise.reject(error.response.data)
});
上述代碼就是請(qǐng)求攔截器,將token放到請(qǐng)求的請(qǐng)求頭中
4、src/router/index.js
router.beforeEach((to, from, next) => {
if(to.path === '/login') {
next();
} else {
let token = localStorage.getItem('token');
if(token === 'null' || token === '') {
next('/login');
}else {
next();
}
}
});
說明
(1)上述代碼是src/router/index.js 的配置 router 要暴露出來,代碼中有export default
**5、src/components/login/login.vue **
//在這個(gè)組件script標(biāo)簽的export default上面引入一個(gè)東西
import { mapMutations } from 'vuex';
//這是methods部分
methods: {
...mapMutations(['setToken']),
login(form){
let _this = this;
if(form.phone === "" || form.password === ""){
_this.$message.error("請(qǐng)輸入手機(jī)號(hào)或密碼");
}else {
this.$axios.post(`/user/check/login`,_this.form).then(res => {
var code = res.data.code;
var mes = res.data.message;
if(code === 1){
/* storage.setItem("token",res.data.data);
_this.token = res.data.data;*/
// _this.setToken({Authorization: _this.token})
// console.log("success");
_this.$message.success('登錄成功');
_this.token = res.data.data;
_this.setToken({token: _this.token});
_this.$router.push({path:"/home"});
var storage = window.localStorage;
//alert(storage.getItem("token"));
if(this.$store.state.token) {
this.$router.push('/home');
console.log(this.$store.state.token.token);
} else {
this.$router.replace('/login');
}
}else{
_this.$message.error(mes);
}
}).catch(function(err){
console.log(err);
_this.$message.error("登錄錯(cuò)誤,請(qǐng)聯(lián)系程序開發(fā)人員!!");
})
}
}
}
說明
(1)
let _this = this;
上述代碼是將this放在_this這個(gè)變量中 ,函數(shù)有普通函數(shù):function(){} 和箭頭函數(shù)
普通函數(shù)的this是指當(dāng)前對(duì)象的引用,這里的當(dāng)前對(duì)象是不確定的,箭頭函數(shù)的this是全局的一個(gè)this 代表的對(duì)象是不可變的,任何方式不可以改變他,具體的區(qū)別參見:箭頭函數(shù)和普通函數(shù)的區(qū)別
_this.setToken({token: _this.token});
上述代碼就是調(diào)用src/store/index.js中的setToken()方法,之所以可以用_this調(diào)用是因?yàn)橹霸趕rc/main.js中將store掛載在vue上了
...mapMutations(['setToken']),
src/components/login/login.vue 中l(wèi)ogin()方法的前面有這樣一段代碼,不知道是干什么的,可能是指定 score 中的方法, 這是我根據(jù)里面的參數(shù)猜的不一定對(duì),希望能有大神指點(diǎn)一二
下面是參考的文章,都寫的很好
1、在vue中如何獲取token,并將token寫進(jìn)header
2、Vue項(xiàng)目中實(shí)現(xiàn)用戶登錄及token驗(yàn)證
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue+SSM實(shí)現(xiàn)驗(yàn)證碼功能
這篇文章主要介紹了vue+SSM實(shí)現(xiàn)驗(yàn)證碼功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-12-12
Element?UI?table參數(shù)中的selectable的使用及遇到坑
這篇文章主要介紹了Element?UI?table參數(shù)中的selectable的使用及遇到的坑,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
vue如何利用axios調(diào)用后臺(tái)api接口
這篇文章主要介紹了vue如何利用axios調(diào)用后臺(tái)api接口問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
vue使用echarts實(shí)現(xiàn)柱狀圖動(dòng)態(tài)排序效果
echarts在前端開發(fā)中實(shí)屬必不可缺的大數(shù)據(jù)可視化工具,這篇文章主要為大家詳細(xì)介紹了vue如何使用echarts實(shí)現(xiàn)柱狀圖動(dòng)態(tài)排序效果,感興趣的可以了解下2023-10-10
詳解Vue中如何實(shí)現(xiàn)圖片處理與濾鏡效果
Vue.js作為一個(gè)靈活的JavaScript框架,可以很容易地與圖像處理庫和濾鏡效果庫集成,以實(shí)現(xiàn)各種圖像處理需求,下面我們就來學(xué)習(xí)一下vue是如何實(shí)現(xiàn)圖片處理與濾鏡效果的吧2023-10-10
Vue如何動(dòng)態(tài)修改el-table的某列數(shù)據(jù)
這篇文章主要介紹了Vue如何動(dòng)態(tài)修改el-table的某列數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
如何用VUE和Canvas實(shí)現(xiàn)雷霆戰(zhàn)機(jī)打字類小游戲
這篇文章主要介紹了如何用VUE和Canvas實(shí)現(xiàn)雷霆戰(zhàn)機(jī)打字類小游戲,麻雀雖小,五臟俱全,對(duì)游戲感興趣的同學(xué),可以參考下,研究里面的原理和實(shí)現(xiàn)方法2021-04-04
vue/cli安裝報(bào)錯(cuò)及解決問題的方法圖文詳解
這篇文章主要給大家介紹了關(guān)于vue/cli安裝報(bào)錯(cuò)及解決問題的方法,如果在安裝@vue/cli時(shí)遇到錯(cuò)誤,大家可以嘗試以下步驟解決,需要的朋友可以參考下2023-07-07
Vue中對(duì)watch的理解(關(guān)鍵是immediate和deep屬性)
watch偵聽器,是Vue實(shí)例的一個(gè)屬性,是用來響應(yīng)數(shù)據(jù)的變化,需要在數(shù)據(jù)變化時(shí)執(zhí)行異步或開銷較大的操作時(shí),這個(gè)方式是最有用的,這篇文章主要介紹了Vue中對(duì)watch的理解,需要的朋友可以參考下2022-11-11

