在vue中獲取token,並將token寫進header的方法
阿新 • • 發佈:2018-11-11
需要準備的東西:Vue+axios+Vuex+Vue-router
1.在login.vue中通過傳送http請求獲取token
前端精品教程:百度網盤下載
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//根據api介面獲取token
var
url =
this
.HOST +
"/session"
;
this
.$axios.post(url, {
username:
this
.loginForm.username, password:
this
.loginForm.pass
}).then(res => {
// console.log(res.data);
this
.$message.success(
'登入成功'
);
let data = res.data; //根據store中set_token方法將token儲存至localStorage/sessionStorage中,data["Authentication-Token"],獲取token的value值
this
.$store.commit(
'set_token'
, data[
"Authentication-Token"
]);
if
(store.state.token) {
this
.$router.push(
'/'
)
console.log(store.state.token)
}
else
{
this
.$router.replace(
'/login'
);
}
}).
catch
(error => {
// this.$message.error(error.status)
this
.loading =
false
this
.loginBtn =
"登入"
this
.$message.error(
'賬號或密碼錯誤'
);
// console.log(error)
})
|
2.在store.js中對token狀態進行監管
前端精品教程:百度網盤下載
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import Vue from
'vue'
import Vuex from
'vuex'
Vue.use(Vuex)
export
default
new
Vuex.Store({
state:{
token:
''
},
mutations:{
set_token(state, token) {
state.token = token
sessionStorage.token = token
},
del_token(state) {
state.token =
''
sessionStorage.removeItem(
'token'
)
}
}
})
|
3.在router/index.js中
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// 頁面重新整理時,重新賦值token
if
(sessionStorage.getItem(
'token'
)) {
store.commit(
'set_token'
, sessionStorage.getItem(
'token'
))
}
const router =
new
Router({
mode:
"history"
,
routes
});
router.beforeEach((to, from, next) => {
if
(to.matched.some(r => r.meta.requireAuth)) {
//這裡的requireAuth為路由中定義的 meta:{requireAuth:true},意思為:該路由新增該欄位,表示進入該路由需要登陸的
if
(store.state.token) {
next();
}
else
{
next({
path:
'/login'
,
query: {redirect: to.fullPath}
})
}
}
else
{
next();
}
})
|
4.在main.js中定義全域性預設配置:
前端精品教程:百度網盤下載
?1 |
Axios.defaults.headers.common[
'Authentication-Token'
] = store.state.token;
|
5.在src/main.js新增攔截器
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// 新增請求攔截器
Axios.interceptors.request.use(config => {
// 在傳送請求之前做些什麼
//判斷是否存在token,如果存在將每個頁面header都新增token
if
(store.state.token){
config.headers.common[
'Authentication-Token'
]=store.state.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)
});
|