提交 192a1b88 authored 作者: sin's avatar sin

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

上级 8a804d65
/* 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}`);
}
}
...@@ -3,6 +3,7 @@ import { notification } from 'antd'; ...@@ -3,6 +3,7 @@ import { notification } from 'antd';
import router from 'umi/router'; import router from 'umi/router';
import hash from 'hash.js'; import hash from 'hash.js';
import { isAntdPro } from './utils'; import { isAntdPro } from './utils';
import { getLoginToken } from './cache';
const codeMessage = { const codeMessage = {
200: '服务器成功返回请求的数据。', 200: '服务器成功返回请求的数据。',
...@@ -82,6 +83,7 @@ export default function request(url, option) { ...@@ -82,6 +83,7 @@ export default function request(url, option) {
const defaultOptions = { const defaultOptions = {
credentials: 'include', credentials: 'include',
}; };
const newOptions = { ...defaultOptions, ...options }; const newOptions = { ...defaultOptions, ...options };
if ( if (
newOptions.method === 'POST' || newOptions.method === 'POST' ||
...@@ -104,6 +106,10 @@ export default function request(url, option) { ...@@ -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; const expirys = options.expirys && 60;
// options.expirys !== false, return the cache, // options.expirys !== false, return the cache,
if (options.expirys !== false) { if (options.expirys !== false) {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论