问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
import axios from 'axios'
import {Message, MessageBox, Notification} from 'element-ui'
import store from '@/store'
import {getToken, removeToken} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { hashByKey, encryptToHex, decryptByHex } from '@/utils/smencrypt'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
//声明存储ajax请求数组
const pending = [];
const removePending = (config, isRequest = false) => {
let key = config.method + ':' + config.url;
for(let p in pending){
if(pending[p].key == key) {
if(!isRequest){
//把这条记录从数组中移除
pending.splice(p, 1);
}
return true;
}
}
if(isRequest){
pending.push({ key: key, value: true});
}
return false;
}
// 创建axios实例
const service = axios.create({
// axios中请求配置有baseURL选项,表示请求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
// 超时
timeout: 30000
})
// request拦截器,自定义request必须拦截登录请求
service.interceptors.request.use(config => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
// get请求映射params参数
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof(value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
console.log(config.data)
// 请求是否加密
const isEnc = process.env.VUE_APP_REQ_ENC
const key = sessionStorage.getItem('sm_key')
if(key && config.data && isEnc && "true" == isEnc){
// 添加报文加密标识
config.headers['is_enc'] = 'true'
config.data = encryptToHex(config.data, key)
}
// 是否重复请求判断
if(removePending(config, true)){
return Promise.reject({message : 'repeat request'})
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res => {
// 移除请求
removePending(res.config);
// 未设置状态码则默认成功状态
const code = res.data.code || 200;
// 响应解密
const isEnc = res.headers['is_enc']
if(res.data && isEnc && "true" == isEnc){
const key = sessionStorage.getItem('sm_key')
const plain = decryptByHex(res.data, key)
res.data = JSON.parse(plain)
}
console.log(res.data)
// 获取错误信息
const msg = errorCode[code] || res.data.msg || errorCode['default']
if (code === 401) {
const skipUrl = res.headers['skip-url'];
if(skipUrl && skipUrl != ''){
// 只有需要认证才会有重定向地址,这个时候清理掉token
removeToken();
sessionStorage.removeItem('sm_key')
// 重定向中断请求
let redirectSkipUrl = Base64.decode(skipUrl)
window.location.href = redirectSkipUrl
return Promise.reject({message : 'redirect request'})
}
MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.href = '/index';
})
})
} else if (code === 500) {
Message({
message: msg,
type: 'error'
})
return Promise.reject(new Error(msg))
} else if (code !== 200) {
Notification.error({
title: msg
})
return Promise.reject('error')
} else {
if(res.config.url.indexOf('/file/download') != -1 ){
return res
}else{
return res.data
}
}
},
error => {
// 移除请求,正常请求响应移除,重复请求不包含config
if(error && error.config){
removePending(error.config);
}
console.log('err' + error)
let {message} = error;
if (message == "Network Error") {
message = "后端接口连接异常";
} else if (message && message.includes("timeout")) {
message = "系统接口请求超时";
} else if (message && message.includes("Request failed with status code")) {
message = "系统接口" + message.substr(message.length - 3) + "异常";
}
if(message && message != '' && message != 'repeat request'){
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
}
return Promise.reject(error)
}
)
export default service
运行结果及报错内容
我的解答思路和尝试过的方法
目前的思路是:
.then(() => {
store.dispatch('LogOut').then(() => {
location.href = '/index';
})
}).catch(action => {
if(action === 'cancel') {
console.log("2")
location.href = '/index';
// history.go(-1);
}
})
在点击取消的时候,做一个if判断,但是实际不知道怎么操作