公司演示版e鹿悦游
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
CjyTravel/common/httpRequest.js

306 lines
8.2 KiB

import * as config from './config';
import cache from './cache';
import aes from "@/common/aes.js";
import store from "@/store/index.js";
// 用于存储正在进行的请求,以便在刷新 token 后重新发送
let requests = [];
let isRefreshingToken = false;
let refreshTokenPromise = null;
const refreshToken = () => {
if (!isRefreshingToken) {
isRefreshingToken = true;
const userInfo = uni.getStorageSync('userInfo');
const refreshTokenValue = userInfo.refreshToken;
if (!refreshTokenValue){
store.commit('setUserInfo', null)
uni.removeStorageSync('userInfo');
setTimeout(() => {
uni.navigateBack({ delta: 1 })
}, 1500)
uni.showToast({
title: '登录过期,请重新登录',
icon: 'none',
mask: true
})
}else{
return module.exports.post(config.refreshToken, { refreshToken: refreshTokenValue }, 'application/json', null, false, false)
.then(response => {
const newAccessToken = response.data.accessToken;
const newRefreshToken = response.data.refreshToken;
userInfo.accessToken = newAccessToken;
userInfo.refreshToken = newRefreshToken;
store.commit('setUserInfo', userInfo)
return newAccessToken;
})
.catch(error => {
isRefreshingToken = false;
return Promise.reject(error);
});
}
} else {
return refreshTokenPromise;
}
};
const requestInterceptor = function (config) {
const tok = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').accessToken:null;
if (tok) {
config.header['Authorization'] = 'Bearer ' + tok;
}
// 添加其他通用预处理逻辑
if (config.data && typeof config.data === 'object') {
for (const key in config.data) {
if (key === 'oldFieldName') {
config.data['newFieldName'] = config.data[key];
delete config.data[key];
}
}
}
return config;
};
const responseInterceptor = function (response,config) {
const code = response[1].data.status || response[1].data.code;
if (code&&code === 401) {
let originalRequest = config;
return new Promise((resolve, reject) => {
// 先将当前请求添加到队列中
requests.push(() => {
originalRequest.header['Authorization'] = 'Bearer ' + store.state.userInfo.accessToken;
return uni.request(originalRequest).then((newResponse) => {
// 如果新的响应还是 401,递归调用直到成功或出现其他错误
if (newResponse[1].data.status === 401 || newResponse[1].data.code === 401) {
return responseInterceptor(newResponse, originalRequest);
} else {
resolve(newResponse[1]);
}
}).catch(reject);
});
// 调用刷新 token 的接口
refreshToken().then(() => {
requests.forEach(cb => cb());
requests = [];
}).catch(reject);
});
}
if(code&&code==400){
store.commit('setUserInfo', null)
console.log(store,'store清除了吗')
uni.removeStorageSync('userInfo');
setTimeout(() => {
uni.navigateBack({ delta: 1 })
}, 1500)
uni.showToast({
title: '登录过期,请重新登录',
icon: 'none',
mask: true
})
}
return response[1];
};
module.exports = {
config: function (name) {
var info = null;
if (name) {
var name2 = name.split(".");
if (name2.length > 1) {
info = configdata[name2[0]][name2[1]] || null;
} else {
info = configdata[name] || null;
}
if (info == null) {
let web_config = cache.get("web_config");
if (web_config) {
if (name2.length > 1) {
info = web_config[name2[0]][name2[1]] || null;
} else {
info = web_config[name] || null;
}
}
}
}
return info;
},
post: function (url, data, headerContentType, tentId, needAes, auth) {
console.log(url, data, headerContentType, tentId, needAes, 'post 请求参数');
if (needAes !== false) {
for (var key in data) {
data[key] = aes.aesMinEncrypt(data[key]);
}
}
headerContentType = headerContentType === "json" ? "application/json" : "application/x-www-form-urlencoded";
let headers = {
"content-type": headerContentType,
'Cache-Control': 'no-cache'
};
if (auth === true) {
const tok = store.state.userInfo.accessToken || uni.getStorageSync('userInfo').accessToken;
headers['Authorization'] = 'Bearer ' + tok;
}
if (tentId && tentId !== "" && tentId !== null && tentId !== undefined) {
headers['tenant-id'] = tentId;
}
return new Promise((succ, error) => {
let config = {
url: url,
data: headerContentType === "application/json" ? JSON.stringify(data) : data,
method: "POST",
header: headers,
xhrFields: {
withCredentials: true
}
};
config = requestInterceptor(config);
uni.request(config).then(result => {
const response = responseInterceptor(result, config);
if (response instanceof Promise) {
response.then(res => {
succ.call(self, res.data);
}).catch(err => {
console.error('POST 请求错误:', err);
error.call(self, err);
});
} else {
succ.call(self, response.data);
}
}).catch(e => {
console.error('POST 请求失败:', e);
error.call(self, e);
});
});
},
put: function (url, data, headerContentType, tentId, needAes, auth) {
console.log(url, data, headerContentType, tentId, needAes, 'get 请求参数');
if (needAes !== false) {
for (var key in data) {
data[key] = aes.aesMinEncrypt(data[key]);
}
}
headerContentType = headerContentType ? headerContentType : "application/x-www-form-urlencoded";
let headers = {
"content-type": headerContentType,
'Cache-Control': 'no-cache'
};
if (auth === true) {
// const tok = store.state.userInfo.accessToken || uni.getStorageSync('userInfo').accessToken;
const tok = uni.getStorageSync('userInfo').accessToken;
headers['Authorization'] = 'Bearer ' + tok;
}
if (tentId && tentId !== "" && tentId !== null && tentId !== undefined) {
headers['tenant-id'] = tentId;
}
return new Promise((succ, error) => {
let config = {
url: url,
data: data,
method: "PUT",
header: headers
};
// 判断如果是 application/x-www-form-urlencoded 且是 PUT 请求,将数据拼接到 URL 上
if (headerContentType === "application/x-www-form-urlencoded" && config.method === "PUT") {
let queryParams = [];
for (let key in data) {
queryParams.push(`${key}=${encodeURIComponent(data[key])}`);
}
config.url += `?${queryParams.join('&')}`;
config.data = {}; // 清空 data,因为数据已经拼接到 URL 上了
}
config = requestInterceptor(config);
uni.request(config).then(result => {
const response = responseInterceptor(result, config);
if (response instanceof Promise) {
response.then(res => {
succ.call(self, res.data);
}).catch(err => {
console.error('PUT 请求错误:', err);
error.call(self, err);
});
} else {
succ.call(self, response.data);
}
}).catch(e => {
console.error('PUT 请求失败:', e);
error.call(self, e);
});
});
},
get: function (url, data, headerContentType, tentId, needAes, auth) {
if (needAes !== false) {
for (var key in data) {
data[key] = aes.aesMinEncrypt(data[key]);
}
}
headerContentType = headerContentType ? headerContentType : "application/x-www-form-urlencoded";
let headers = {
"content-type": headerContentType,
'Cache-Control': 'no-cache'
};
if (auth === true) {
// const tok = store.state.userInfo.accessToken || uni.getStorageSync('userInfo').accessToken;
const tok = uni.getStorageSync('userInfo').accessToken;
headers['Authorization'] = 'Bearer ' + tok;
}
if (tentId && tentId !== "" && tentId !== null && tentId !== undefined) {
headers['tenant-id'] = tentId;
}
return new Promise((succ, error) => {
let config = {
url: url,
data: data,
method: "GET",
header: headers
};
console.log('config'.config)
config = requestInterceptor(config);
uni.request(config).then(result => {
const response = responseInterceptor(result, config);
if (response instanceof Promise) {
response.then(res => {
succ.call(self, res.data);
}).catch(err => {
console.error('GET 请求错误:', err);
error.call(self, err);
});
} else {
succ.call(self, response.data);
}
}).catch(e => {
console.error('GET 请求失败:', e);
error.call(self, e);
});
});
}
};