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、問(wèn)題
做一個(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保存下來(lái),后面發(fā)送請(qǐng)求的時(shí)候在拿出來(lái);
3、在發(fā)送每個(gè)請(qǐng)求時(shí)都要把token加到請(qǐng)求頭里,寫一個(gè)全局的攔截器。
4、記錄和說(shuō)明
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;
說(shuō)明:
(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)來(lái)的是一個(gè)對(duì)象(即使你覺的你傳進(jìn)來(lái)的是一個(gè)字符串,不知道為什么會(huì)被放到object里去),傳進(jìn)來(lái)的對(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è)頁(yè)面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)前頁(yè)面 }) } } return Promise.reject(error.response.data) });
說(shuō)明
(1)這個(gè)是全部的代碼,不一定都和這個(gè)一樣,下面說(shuō)說(shuō)用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 來(lái)獲取store
(3)
// 添加請(qǐng)求攔截器 axios.interceptors.request.use(config => { // 在發(fā)送請(qǐng)求之前做些什么 //判斷是否存在token,如果存在將每個(gè)頁(yè)面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)前頁(yè)面 }) } } 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(); } } });
說(shuō)明
(1)上述代碼是src/router/index.js 的配置 router 要暴露出來(lái),代碼中有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ā)人員!!"); }) } } }
說(shuō)明
(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 項(xiàng)目中引入 tinymce 富文本編輯器的完整代碼
這篇文章主要介紹了在 Vue 項(xiàng)目中引入 tinymce 富文本編輯器的實(shí)例代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-05-05Vue Extends 擴(kuò)展選項(xiàng)用法完整實(shí)例
這篇文章主要介紹了Vue Extends 擴(kuò)展選項(xiàng)用法,結(jié)合完整實(shí)例形式分析了Vue Extends 擴(kuò)展選項(xiàng)相關(guān)使用技巧與操作注意事項(xiàng),需要的朋友可以參考下2019-09-09vue實(shí)現(xiàn)把頁(yè)面導(dǎo)出成word文件的方法
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)把頁(yè)面導(dǎo)出成word文件的方法,文中的實(shí)現(xiàn)步驟講解詳細(xì),并且有詳細(xì)的代碼示例,需要的小伙伴可以參考一下2023-10-10如何為vuex實(shí)現(xiàn)帶參數(shù)的 getter和state.commit
這篇文章主要介紹了如何為vuex實(shí)現(xiàn)帶參數(shù)的getter和state.commit,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01在Vuex使用dispatch和commit來(lái)調(diào)用mutations的區(qū)別詳解
今天小編就為大家分享一篇在Vuex使用dispatch和commit來(lái)調(diào)用mutations的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09VUE實(shí)現(xiàn)大轉(zhuǎn)盤抽獎(jiǎng)
營(yíng)運(yùn)三寶(九宮格、大轉(zhuǎn)盤、老虎機(jī),當(dāng)然此三寶當(dāng)然是最基礎(chǔ)的營(yíng)銷運(yùn)營(yíng)手段),本片文章聊聊大轉(zhuǎn)盤,轉(zhuǎn)盤的實(shí)現(xiàn)邏輯應(yīng)該是營(yíng)銷方案較為簡(jiǎn)單的一種了,本文將介紹如何實(shí)現(xiàn)大轉(zhuǎn)盤抽獎(jiǎng),感興趣的朋友可以參考下2021-05-05Element-Plus之el-col與el-row快速布局
el-col是el-row的子元素,下面這篇文章主要給大家介紹了關(guān)于Element-Plus之el-col與el-row快速布局的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09