fix cookie token bug

This commit is contained in:
Pan 2017-07-20 14:27:47 +08:00
parent 4321f5845f
commit 822c59bdba
4 changed files with 24 additions and 7 deletions

View File

@ -11,6 +11,7 @@ import 'nprogress/nprogress.css'
import 'normalize.css/normalize.css'
import '@/assets/iconfont/iconfont'
import IconSvg from '@/components/Icon-svg/index.vue'
import { getToken } from '@/utils/auth'
Vue.config.productionTip = false
@ -20,7 +21,7 @@ Vue.component('icon-svg', IconSvg)
const whiteList = ['/login'];
router.beforeEach((to, from, next) => {
NProgress.start();
if (store.getters.token) {
if (getToken()) {
if (to.path === '/login') {
next({ path: '/' });
} else {

View File

@ -1,9 +1,9 @@
import { login, logout, getInfo } from '@/api/login';
import Cookies from 'js-cookie';
import { getToken, setToken, removeToken } from '@/utils/auth';
const user = {
state: {
token: Cookies.get('Admin-Token'),
token: getToken(),
name: '',
avatar: '',
roles: []
@ -31,7 +31,7 @@ const user = {
return new Promise((resolve, reject) => {
login(email, userInfo.password).then(response => {
const data = response.data;
Cookies.set('Admin-Token', data.token);
setToken(data.token);
commit('SET_TOKEN', data.token);
resolve();
}).catch(error => {
@ -62,7 +62,7 @@ const user = {
logout(state.token).then(() => {
commit('SET_TOKEN', '');
commit('SET_ROLES', []);
Cookies.remove('Admin-Token');
removeToken();
resolve();
}).catch(error => {
reject(error);
@ -74,7 +74,7 @@ const user = {
FedLogOut({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '');
Cookies.remove('Admin-Token');
removeToken();
resolve();
});
}

15
src/utils/auth.js Normal file
View File

@ -0,0 +1,15 @@
import Cookies from 'js-cookie'
const TokenKey = 'Admin-Token'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
return Cookies.remove(TokenKey)
}

View File

@ -1,6 +1,7 @@
import axios from 'axios';
import { Message } from 'element-ui';
import store from '../store';
import { getToken } from '@/utils/auth';
// 创建axios实例
@ -12,7 +13,7 @@ const service = axios.create({
// request拦截器
service.interceptors.request.use(config => {
if (store.getters.token) {
config.headers['X-Token'] = store.getters.token; // 让每个请求携带自定义token 请根据实际情况自行修改
config.headers['X-Token'] = getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
}
return config;
}, error => {