From 192a1b8850c6ad54206a3f310b52da9ad13d3db4 Mon Sep 17 00:00:00 2001 From: sin <2943460818@qq.com> Date: Mon, 4 Mar 2019 11:33:02 +0800 Subject: [PATCH] =?UTF-8?q?-=20=E6=8B=A6=E6=88=AA=E7=99=BB=E9=99=86?= =?UTF-8?q?=E5=90=8E=EF=BC=8C=E6=89=80=E6=9C=89=E8=AF=B7=E6=B1=82=20header?= =?UTF-8?q?=20=E5=8A=A0=E4=B8=8A=E6=B7=BB=E5=8A=A0=20token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- admin-web/src/utils/cache.js | 42 ++++++++++++++++++++++++++++++++++ admin-web/src/utils/request.js | 6 +++++ 2 files changed, 48 insertions(+) create mode 100644 admin-web/src/utils/cache.js diff --git a/admin-web/src/utils/cache.js b/admin-web/src/utils/cache.js new file mode 100644 index 000000000..3d44cc8ca --- /dev/null +++ b/admin-web/src/utils/cache.js @@ -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}`); + } +} diff --git a/admin-web/src/utils/request.js b/admin-web/src/utils/request.js index 78aa4635c..9401d1ec3 100644 --- a/admin-web/src/utils/request.js +++ b/admin-web/src/utils/request.js @@ -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) {