完整axios 带token 失效自动刷新
"use strict";
import axios from "axios";
import router from "../router";
import { base } from "./baseUrl";
let _this = this;
axios.interceptors.request.use(
config => {
return config;
},
err => {
alert("请求超时!");
return Promise.resolve(err);
}
);
axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;
// 响应拦截器
axios.interceptors.response.use(
response => {
console.log(response, "response");
if (response) {
console.log(response);
switch (response.data.code) {
case 4011: //与后台约定登录失效的返回码,根据实际情况处
if (sessionStorage.getItem("token")) {
router.push("/my");
} else {
sessionStorage.clear();
router.push({
name: "checkTel",
params: {
id: 1,
openId: response.data.message
}
});
}
}
}
return response;
},
err => {
let config = err.config;
// axiosRetry(config)
if (err.config && err.response && err.response.status === "401") {
return updateToken().then(token => {
return axios.request(config);
});
}
// If config does not exist or the retry option is not set, reject
if (!config || !config.retry) return Promise.reject(err);
// Set the variable for keeping track of the retry count
config.__retryCount = config.__retryCount || 0;
// Check if we've maxed out the total number of retries
if (config.__retryCount >= config.retry) {
// Reject with the error
return Promise.reject(err);
}
// Increase the retry count
config.__retryCount += 1;
// Create new promise to handle exponential backoff
var backoff = new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, config.retryDelay || 1);
});
// Return the promise in which recalls axios to retry the request
return backoff.then(function() {
return axios(config);
});
}
);
//是否正在刷新标记
let isRefresh = false;
// 重试队列,每一项将是一个待执行的函数形式
let requests = [];
export const postRequest = (url, params, Func, isJson) => {
axios({
method: "post",
url: `${base}${url}`,
data: params,
transformRequest: [
function(data) {
let ret = "";
for (let it in data) {
if (isJson === 1) {
ret = data[it];
} else {
ret +=
encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
}
}
return ret;
}
],
headers: {
"Content-Type":
isJson === 1 ? "application/json" : "application/x-www-form-urlencoded",
authorization: sessionStorage.getItem("userName"),
token: sessionStorage.getItem("token"),
clientAppId: sessionStorage.getItem("clientAppId"),
dingAppId: sessionStorage.getItem("dingAppId")
}
}).then(data => {
console.log(data.data);
if (data.data.code === 200) {
Func(data.data.data);
} else if (data.data.code === 406) {
alert(data.data.message);
} else if (data.data.code === 401) {
alert("认证失败");
} else if (
data.data.code === 400 ||
data.data.code === 505 ||
data.data.code === 404 ||
data.data.code === 500
) {
alert("网络异常");
} else if (data.data.code === 4013) {
router.push({
name: "checkTel",
params: {
id: 1,
openId: data.data.message
}
});
} else if (data.data.code === 4011) {
if (sessionStorage.getItem("token")) {
router.push("/my");
} else {
sessionStorage.clear();
}
} else if (data.data.code === 4012) {
//需要进行刷新token
if (!isRefresh) {
isRefresh = true;
postRequest(
"token/refresh",
{
authorization: sessionStorage.getItem("userName"),
refresh_token: sessionStorage.getItem("refreshToken")
},
"post",
res => {
//缓存新的token
let token = res.token;
let principal = res.principal;
let refreshToken = res.refreshToken;
sessionStorage.setItem("token", token);
sessionStorage.setItem("principal", principal);
sessionStorage.setItem("refreshToken", refreshToken);
requests.forEach(cb => cb());
requests = [];
return postRequest(url, params, Func, isJson);
}
).finally(() => {
isRefresh = false;
});
} else {
// 将resolve放进队列,用一个函数形式来保存,等token刷新后直接执行
return new Promise(resolve => {
requests.push(() => {
resolve(postRequest(url, params, Func, isJson));
});
});
}
}
});
};
export const postRequestN9 = (url, params, Func) => {
axios({
method: "post",
url: `${url}`,
data: params,
transformRequest: [
function(data) {
let ret = "";
for (let it in data) {
ret +=
encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
}
return ret;
}
]
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
// }
}).then(data => {
// console.log(data,'返回信息code')
if (data.data.StateCode === 0) {
Func(data.data.Result);
} else if (data.data.StateCode === 2) {
alert(data.data.ErrorMsg);
} else if (data.data.StateCode === 4) {
alert(data.data.ErrorMsg);
} else if (data.data.StateCode === 3) {
alert(data.data.ErrorMsg);
} else {
alert("网络异常");
}
sessionStorage.setItem("btn-isDisabled", false);
});
};
export const uploadFileRequestN9 = (url, params) => {
return axios({
method: "post",
url: `${url}`,
data: params,
headers: {
"Content-Type": "multipart/form-data"
}
});
};
export const uploadFileRequest = (url, params) => {
return axios({
method: "post",
url: `${base}${url}`,
data: params,
headers: {
"Content-Type": "multipart/form-data",
authorization: sessionStorage.getItem("userName"),
token: sessionStorage.getItem("token"),
clientAppId: sessionStorage.getItem("clientAppId")
}
});
};
export const putRequest = (url, params) => {
return axios({
method: "put",
url: `${base}${url}`,
data: params,
transformRequest: [
function(data) {
let ret = "";
for (let it in data) {
ret +=
encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
}
return ret;
}
],
headers: {
"Content-Type": "application/x-www-form-urlencoded",
authorization: sessionStorage.getItem("userName"),
token: sessionStorage.getItem("token"),
clientAppId: sessionStorage.getItem("clientAppId")
}
});
};
export const deleteRequest = url => {
return axios({
method: "delete",
url: `${base}${url}`
});
};
export const getRequest = (url, params, Func) => {
return axios({
method: "get",
url: `${base}${url}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
authorization: sessionStorage.getItem("userName"),
token: sessionStorage.getItem("token"),
clientAppId: sessionStorage.getItem("clientAppId")
}
}).then(data => {
if (data.data.code === 200) {
Func(data.data.data);
}
});
};
作者:人参,每篇随笔皆原创(除非注明原作者的随笔),欢迎指正!