Vue項目中token驗證登錄(前端部分)
本文實例為大家分享了Vue項目中token驗證登錄的具體代碼,供大家參考,具體內(nèi)容如下
1、前言
最近在做畢業(yè)設(shè)計,我是做后端的,前端并不是很懂,看vue這個框架看了近兩個禮拜才有點入門的感覺,所以這篇文章寫的可能不怎么好,僅作記錄,有什么不對或不足的地方歡迎大神指出。
2、問題
做一個登錄界面,我選擇的是用token進行驗證登錄,我用的前端框架是Vue.js 和 element-ui,如何在vue 中使用token進行驗證登錄。
3、思考
1、利用token進行驗證登錄,用戶進行登錄操作時,后臺會生成一個token返回給前端,由前端 將這個token放到請求頭中(這個是百度的,一般都是放在請求頭),并且此后調(diào)用接口都要把token放到請求的請求頭傳回給后臺;
2、用戶登錄后,前端需要把token保存下來,后面發(fā)送請求的時候在拿出來;
3、在發(fā)送每個請求時都要把token加到請求頭里,寫一個全局的攔截器。
4、記錄和說明
1、 在src文件夾(我的vue項目是用vue-cli 腳手架創(chuàng)建的)下創(chuàng)建一個store文件夾,在store中創(chuàng)建一個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)容之前,要在你的項目里安裝Vuex ,這里只提供npm的安裝方法,在項目根目錄處打開cmd 輸入下面的命令,后回車
npm install vuex --save
(2) 在這個store/store/index.js中 這段代碼token.token , 是因為在login.vue中調(diào)用這個放法傳進來的是一個對象(即使你覺的你傳進來的是一個字符串,不知道為什么會被放到object里去),傳進來的對象里有token這個屬性
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/>'
});
// 添加請求攔截器
axios.interceptors.request.use(config => {
// 在發(fā)送請求之前做些什么
//判斷是否存在token,如果存在將每個頁面header都添加token
if(store.state.token){
config.headers.common['Authorization']=store.state.token.token
}
return config;
}, error => {
// 對請求錯誤做些什么
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}//登錄成功后跳入瀏覽的當前頁面
})
}
}
return Promise.reject(error.response.data)
});
說明
(1)這個是全部的代碼,不一定都和這個一樣,下面說說用token驗證,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)
// 添加請求攔截器
axios.interceptors.request.use(config => {
// 在發(fā)送請求之前做些什么
//判斷是否存在token,如果存在將每個頁面header都添加token
if(store.state.token){
config.headers.common['Authorization']=store.state.token.token
}
return config;
}, error => {
// 對請求錯誤做些什么
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}//登錄成功后跳入瀏覽的當前頁面
})
}
}
return Promise.reject(error.response.data)
});
上述代碼就是請求攔截器,將token放到請求的請求頭中
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 **
//在這個組件script標簽的export default上面引入一個東西
import { mapMutations } from 'vuex';
//這是methods部分
methods: {
...mapMutations(['setToken']),
login(form){
let _this = this;
if(form.phone === "" || form.password === ""){
_this.$message.error("請輸入手機號或密碼");
}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("登錄錯誤,請聯(lián)系程序開發(fā)人員??!");
})
}
}
}
說明
(1)
let _this = this;
上述代碼是將this放在_this這個變量中 ,函數(shù)有普通函數(shù):function(){} 和箭頭函數(shù)
普通函數(shù)的this是指當前對象的引用,這里的當前對象是不確定的,箭頭函數(shù)的this是全局的一個this 代表的對象是不可變的,任何方式不可以改變他,具體的區(qū)別參見:箭頭函數(shù)和普通函數(shù)的區(qū)別
_this.setToken({token: _this.token});
上述代碼就是調(diào)用src/store/index.js中的setToken()方法,之所以可以用_this調(diào)用是因為之前在src/main.js中將store掛載在vue上了
...mapMutations(['setToken']),
src/components/login/login.vue 中l(wèi)ogin()方法的前面有這樣一段代碼,不知道是干什么的,可能是指定 score 中的方法, 這是我根據(jù)里面的參數(shù)猜的不一定對,希望能有大神指點一二
下面是參考的文章,都寫的很好
1、在vue中如何獲取token,并將token寫進header
2、Vue項目中實現(xiàn)用戶登錄及token驗證
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在 Vue 項目中引入 tinymce 富文本編輯器的完整代碼
這篇文章主要介紹了在 Vue 項目中引入 tinymce 富文本編輯器的實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-05-05
vue實現(xiàn)把頁面導(dǎo)出成word文件的方法
這篇文章主要為大家詳細介紹了vue實現(xiàn)把頁面導(dǎo)出成word文件的方法,文中的實現(xiàn)步驟講解詳細,并且有詳細的代碼示例,需要的小伙伴可以參考一下2023-10-10
如何為vuex實現(xiàn)帶參數(shù)的 getter和state.commit
這篇文章主要介紹了如何為vuex實現(xiàn)帶參數(shù)的getter和state.commit,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
在Vuex使用dispatch和commit來調(diào)用mutations的區(qū)別詳解
今天小編就為大家分享一篇在Vuex使用dispatch和commit來調(diào)用mutations的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
Element-Plus之el-col與el-row快速布局
el-col是el-row的子元素,下面這篇文章主要給大家介紹了關(guān)于Element-Plus之el-col與el-row快速布局的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-09-09

