- 拦截登陆后,所有请求 header 加上添加 token

pull/1/head
sin 2019-03-04 11:33:02 +08:00
parent 8a804d654e
commit 192a1b8850
2 changed files with 48 additions and 0 deletions

View File

@ -0,0 +1,42 @@
/* eslint-disable */
// localStorage 操作
const cacheKeys = {
accessTokenKey: 'accessToken',
refreshTokenKey: 'refreshToken',
};
///
/// 设置 loginToken分为 accessToken 和 refreshToken
export function setLoginToken(accessToken, refreshToken) {
setLocalStorage(cacheKeys.accessTokenKey, accessToken);
setLocalStorage(cacheKeys.refreshTokenKey, refreshToken);
}
export function getLoginToken() {
const res = {};
cacheKeys[cacheKeys.accessTokenKey] = getLocalStorage(cacheKeys.accessTokenKey);
cacheKeys[cacheKeys.refreshTokenKey] = getLocalStorage(cacheKeys.refreshTokenKey);
return res;
}
///
/// 设置 localStorage 公共方法
function setLocalStorage(key, value) {
try {
localStorage.setItem(key, value);
} catch (e) {
throw new Error(`localStorage 设置错误! ${e}`);
}
}
function getLocalStorage(key) {
try {
return localStorage.getItem(key);
} catch (e) {
throw new Error(`localStorage 获取错误! ${e}`);
}
}

View File

@ -3,6 +3,7 @@ import { notification } from 'antd';
import router from 'umi/router';
import hash from 'hash.js';
import { isAntdPro } from './utils';
import { getLoginToken } from './cache';
const codeMessage = {
200: '服务器成功返回请求的数据。',
@ -82,6 +83,7 @@ export default function request(url, option) {
const defaultOptions = {
credentials: 'include',
};
const newOptions = { ...defaultOptions, ...options };
if (
newOptions.method === 'POST' ||
@ -104,6 +106,10 @@ export default function request(url, option) {
}
}
// 将登陆的 accessToken 放到 header
const loginToken = getLoginToken();
newOptions.headers.Authorization = loginToken.accessToken;
const expirys = options.expirys && 60;
// options.expirys !== false, return the cache,
if (options.expirys !== false) {