token 解析问题处理

master
Chopper 2021-06-22 17:36:07 +08:00
parent d3576b691c
commit 8e239a5bbf
1 changed files with 52 additions and 52 deletions

View File

@ -1,27 +1,27 @@
// import Vue from 'vue'; // import Vue from 'vue';
import axios from "axios"; import axios from 'axios';
import https from "https"; import https from 'https';
import { Message, Spin, Modal } from "view-design"; import { Message, Spin, Modal } from 'view-design';
import Storage from "./storage"; import Storage from './storage';
import config from "@/config"; import config from '@/config';
import router from "../router/index.js"; import router from '../router/index.js';
import store from "../vuex/store"; import store from '../vuex/store';
import { handleRefreshToken } from "@/api/index"; import { handleRefreshToken } from '@/api/index';
const qs = require("qs"); const qs = require('qs');
export const buyerUrl = export const buyerUrl =
process.env.NODE_ENV === "development" process.env.NODE_ENV === 'development'
? config.api_dev.buyer ? config.api_dev.buyer
: config.api_prod.buyer; : config.api_prod.buyer;
export const commonUrl = export const commonUrl =
process.env.NODE_ENV === "development" process.env.NODE_ENV === 'development'
? config.api_dev.common ? config.api_dev.common
: config.api_prod.common; : config.api_prod.common;
export const managerUrl = export const managerUrl =
process.env.NODE_ENV === "development" process.env.NODE_ENV === 'development'
? config.api_dev.manager ? config.api_dev.manager
: config.api_prod.manager; : config.api_prod.manager;
export const sellerUrl = export const sellerUrl =
process.env.NODE_ENV === "development" process.env.NODE_ENV === 'development'
? config.api_dev.seller ? config.api_dev.seller
: config.api_prod.seller; : config.api_prod.seller;
// 创建axios实例 // 创建axios实例
@ -35,7 +35,7 @@ const service = axios.create({
}), }),
paramsSerializer: params => paramsSerializer: params =>
qs.stringify(params, { qs.stringify(params, {
arrayFormat: "repeat" arrayFormat: 'repeat'
}) })
}); });
@ -44,15 +44,15 @@ service.interceptors.request.use(
config => { config => {
const { loading } = config; const { loading } = config;
// 如果是put/post请求用qs.stringify序列化参数 // 如果是put/post请求用qs.stringify序列化参数
const isPutPost = config.method === "put" || config.method === "post"; const isPutPost = config.method === 'put' || config.method === 'post';
const isJson = config.headers["Content-Type"] === "application/json"; const isJson = config.headers['Content-Type'] === 'application/json';
const isFile = config.headers["Content-Type"] === "multipart/form-data"; const isFile = config.headers['Content-Type'] === 'multipart/form-data';
if (isPutPost && isJson) { if (isPutPost && isJson) {
config.data = JSON.stringify(config.data); config.data = JSON.stringify(config.data);
} }
if (isPutPost && !isFile && !isJson) { if (isPutPost && !isFile && !isJson) {
config.data = qs.stringify(config.data, { config.data = qs.stringify(config.data, {
arrayFormat: "repeat" arrayFormat: 'repeat'
}); });
} }
/** 配置全屏加载 */ /** 配置全屏加载 */
@ -60,16 +60,16 @@ service.interceptors.request.use(
config.loading = Spin.show(); config.loading = Spin.show();
} }
const uuid = Storage.getItem("uuid"); const uuid = Storage.getItem('uuid');
config.headers["uuid"] = uuid; config.headers['uuid'] = uuid;
// 获取访问Token // 获取访问Token
let accessToken = Storage.getItem("accessToken"); let accessToken = Storage.getItem('accessToken');
if (accessToken && config.needToken) { if (accessToken && config.needToken) {
config.headers["accessToken"] = accessToken; config.headers['accessToken'] = accessToken;
// 解析当前token时间 // 解析当前token时间
let jwtData = JSON.parse( let jwtData = JSON.parse(
decodeURIComponent(escape(window.atob(accessToken.split(".")[1]))) decodeURIComponent(escape(window.atob(accessToken.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))))
); );
if (jwtData.exp < Math.round(new Date() / 1000)) { if (jwtData.exp < Math.round(new Date() / 1000)) {
refresh() refresh()
@ -85,31 +85,31 @@ service.interceptors.request.use(
async function refresh () { async function refresh () {
const getTokenRes = await refreshToken(); const getTokenRes = await refreshToken();
if (getTokenRes === "success") { if (getTokenRes === 'success') {
// 刷新token // 刷新token
if (isRefreshToken === 1) { if (isRefreshToken === 1) {
error.response.config.headers.accessToken = Storage.getItem( error.response.config.headers.accessToken = Storage.getItem(
"accessToken" 'accessToken'
); );
return service(error.response.config); return service(error.response.config);
} else { } else {
router.go(0); router.go(0);
} }
} else { } else {
Storage.removeItem("accessToken"); Storage.removeItem('accessToken');
Storage.removeItem("refreshToken"); Storage.removeItem('refreshToken');
Storage.removeItem("userInfo"); Storage.removeItem('userInfo');
Storage.setItem("cartNum", 0); Storage.setItem('cartNum', 0);
store.commit("SET_CARTNUM", 0); store.commit('SET_CARTNUM', 0);
console.log("1111"); console.log('1111');
Modal.confirm({ Modal.confirm({
title: "请登录", title: '请登录',
content: "<p>请登录后执行此操作</p>", content: '<p>请登录后执行此操作</p>',
okText: "立即登录", okText: '立即登录',
cancelText: "继续浏览", cancelText: '继续浏览',
onOk: () => { onOk: () => {
router.push({ router.push({
path: "/login", path: '/login',
query: { query: {
rePath: router.history.current.path, rePath: router.history.current.path,
query: JSON.stringify(router.history.current.query) query: JSON.stringify(router.history.current.query)
@ -146,9 +146,9 @@ service.interceptors.response.use(
} else { } else {
if (error.message) { if (error.message) {
let _message = let _message =
error.code === "ECONNABORTED" error.code === 'ECONNABORTED'
? "连接超时,请稍候再试!" ? '连接超时,请稍候再试!'
: "网络错误,请稍后再试!"; : '网络错误,请稍后再试!';
Message.error(errorData.message || _message); Message.error(errorData.message || _message);
} }
} }
@ -171,10 +171,10 @@ const closeLoading = target => {
}; };
export const Method = { export const Method = {
GET: "get", GET: 'get',
POST: "post", POST: 'post',
PUT: "put", PUT: 'put',
DELETE: "delete" DELETE: 'delete'
}; };
export default function request (options) { export default function request (options) {
@ -192,13 +192,13 @@ function getTokenDebounce() {
return function () { return function () {
if (!lock) { if (!lock) {
lock = true; lock = true;
let oldRefreshToken = Storage.getItem("refreshToken"); let oldRefreshToken = Storage.getItem('refreshToken');
handleRefreshToken(oldRefreshToken) handleRefreshToken(oldRefreshToken)
.then(res => { .then(res => {
if (res.success) { if (res.success) {
let { accessToken, refreshToken } = res.result; let { accessToken, refreshToken } = res.result;
Storage.setItem("accessToken", accessToken); Storage.setItem('accessToken', accessToken);
Storage.setItem("refreshToken", refreshToken); Storage.setItem('refreshToken', refreshToken);
success = true; success = true;
lock = false; lock = false;
@ -220,9 +220,9 @@ function getTokenDebounce() {
if (!lock) { if (!lock) {
clearInterval(timer); clearInterval(timer);
if (success) { if (success) {
resolve("success"); resolve('success');
} else { } else {
resolve("fail"); resolve('fail');
} }
} }
}, 500); // 轮询时间间隔 }, 500); // 轮询时间间隔