lj_zhgd-app/zhgd-app/service/request.js

313 lines
8.4 KiB
JavaScript
Raw Normal View History

2024-08-06 16:27:09 +08:00
import cookie from 'js-cookie'
import CONFIG from './config.js'
import CONSTANT from './constant.js'
// import utils from '@/assets/js/util/utils.js';
/**
* 请求接口地址处理
*/
const _config = {
env: process.env.NODE_ENV,
serverUrl() {
console.log(this.env)
switch (this.env) {
case 'development':
return CONFIG.TEST_URL;
case 'production':
return CONFIG.PROD_URL;
}
},
//新增一个是否开发环境
isDev() {
return this.env === 'development';
},
api(url, mock) {
// 判断运行环境
let href = ''
//此处不把系统服务端地址暴露在本地缓存中,完全按照 identity 来判断
// let identity = uni.getStorageSync('identity');
let identity = 'Test'
if (identity === 'Test') {
href = `${CONFIG.TEST_URL}${url}`
} else if (identity === 'Poc') {
href = `${CONFIG.POC_URL}${url}`
} else {
href = `${CONFIG.PROD_URL}${url}`
}
// console.log(identity, href, 'identity, href')
// // 如果 mock 为 true使用RAP2 联调地址(开发使用)
// if (mock === 1) {
// return `http://rap2.tydiczt.cn:8001/app/mock/230${url}`;
// } else if (mock) {
// return `http://rap2.tydiczt.cn:8001/app/mock/228${url}`;
// } else {
// return href;
// }
// console.log(href, 'href');
return href;
}
};
/**
* 接口请求统一处理方法
*/
const _fn = {
/**
* 接口调用成功的回调函数
*/
success(resolve, reject, res) {
// console.log(res, 'response');
// header token 放到外围记录,放在里面可能会丢失
if (res?.header?.Authorization) {
// console.log(res.header.authorization, 'res.header.authorization')
// H5里面 authorization 首字母小写
uni.setStorageSync('auth-token', res.header.Authorization)
// #ifdef H5
cookie.set('admin-token', res.header.Authorization)
// #endif
}
else if (res?.header?.Authorization) {
// 安卓 Authorization 首字母大写
// console.log(res.header.Authorization, 'res.header.Authorization')
uni.setStorageSync('auth-token', res.header.Authorization)
// #ifdef H5
cookie.set('admin-token', res.header.Authorization)
// #endif
}
// 接口返回res.data是string类型需转成json类型
if (typeof res.data === 'string') {
try {
res.data = JSON.parse(res.data);
} catch (e) {
console.error(`==接口出参string转json失败`);
}
}
switch (res.data.code) {
case 200:
// console.log('200',res)
//如果没有code属性表示不是后端返回不判断
if (res.data.code === 200) {
resolve(res.data);
} else {
reject(res.data)
}
break;
case 401:
if (res.data.code !== 200) {
// 未登录或Token过期
if (res.data.code === 401) {
console.log('401')
// 清除登录信息的缓存数据
uni.removeStorageSync('auth-token');
// 获取当前页面的路由名
const routes = getCurrentPages(); // 获取当前打开过的页面路由数组
const curRoutePath = routes[routes.length - 1].route; // 获取当前页面路由
const curRouteSplit = curRoutePath.split('/');
const curRouteName = curRouteSplit[curRouteSplit.length - 1]; // 获取当前页面的路由名称
// 启动页获取用户信息,也不能再跳转回来,
// 当前页面如果是登录页就不再跳转 login
if (!['blank', 'login'].includes(curRouteName)) {
//对应页面退出后,把页面地址作为参数传给登录页面
let rediect = routes[routes.length - 1]['$page']['fullPath']
console.log(rediect, 'rediect')
// 记录到缓存需要首页跳转
// 加个判断如果页面url带的参数过长不记录首页跳转
if (rediect && rediect.length < 100)
uni.setStorageSync('rediect', rediect)
}
uni.reLaunch({
url: '/pages/login/login'
});
}
else {
reject(res.data)
if (_config.isDev())
console.error(`==网络异常==`, res);
// uni.showToast({
// title: res.data.message || '接口异常',
// icon: 'none'
// });
}
}
break;
default:
// console.log(res);
reject(res.data);
if (_config.isDev())
console.error(`==网络异常==`, res);
uni.showToast({
title: res?.data?.msg || '网络异常',
icon: 'none'
});
break;
}
},
/**
* 接口调用失败的回调函数
*/
fail(resolve, reject, res) {
console.error('==接口请求失败==', res);
reject(res.data);
}
};
/**
* @param {Object} 接受一个对象作为参数
* {
* url: url地址,
* data: 请求参数,
* mock: 启用 rap2 联调测试
* method: 请求方法默认'GET',
* contentType: 数据类型默认'json',
* disableLoad: 是否禁用加载框默认false
* }
* @return {Promise} 返回一个Promise对象
* @desc '只有在接口返回的statusCode === 200 并且 res.data.status === 1才resolve其他情况为reject'
*/
// 带上设备信息
let deviceInfo = null
let os = null
const request = ({
url,
data = {},
mock = false,
option,
method = 'GET',
// contentType = 'json'
}) => {
let contentType = 'application/x-www-form-urlencoded'
let timeout = 20000
// console.log(option)
if (option.contentType === 'form') {
contentType = 'application/x-www-form-urlencoded';
}
if (option.contentType === 'upload') {
contentType = 'multipart/form-data';
}
if(option.timeout) {
timeout = option.timeout
}
// else {
// contentType = 'multipart/form-data';
// }
if (deviceInfo === null) {
let deviceInfoObj = uni.getSystemInfoSync()
delete deviceInfoObj.appName
deviceInfo = JSON.stringify(deviceInfoObj)
os = deviceInfoObj.platform
}
const header = {
'Content-Type': contentType,
// H5 方式 token 存在 cookie 的 admin-token 中因为需要跨项目共享token
'Authorization': uni.getStorageSync('auth-token') ?? '',
// #ifndef H5
'cookie': '', //此处由于APP会自动带上H5的cookie所以APP此处cookie置空
// #endif
// 'version': CONSTANT.VERSIONNAME,
// deviceInfo,
// os,
// #ifdef H5 || MP-WEIXIN
// 'loginType': 'reserveH5',
// #endif
// #ifdef APP-PLUS
'loginType': 'app',
// #endif
}
// console.log(JSON.stringify(option.header) , 'option.header')
if(option.header) {
Object.assign(header, option.header);
}
// console.log(header, 'request header');
// console.log(data, 'request data');
// console.log(url, header, 'header.loginType')
// console.log(_config.api(url, mock), header, 'request header');
return new Promise((resolve, reject) => {
uni.request({
url: _config.api(url, mock),
data,
method,
header,
dataType: 'json',
responseType: 'text',
timeout,
success: function(res) {
_fn.success(resolve, reject, res);
// resolve(res.data);
},
fail: function(res) {
_fn.fail(resolve, reject, res);
// reject(res.data);
}
})
})
}
/**
* @param {Object} 接受一个对象作为参数
* {
* url: url地址,
* filePath: 文件路径,
* disableLoad: 是否禁用加载框默认false
* }
* @return {Promise} 返回一个Promise对象
* @desc '只有在接口返回的statusCode === 200 并且 res.data.status === 1才resolve其他情况为reject'
*/
const upload = ({
url,
filePath = '',
disableLoad = false
}) => {
if (deviceInfo === null) {
let deviceInfoObj = uni.getSystemInfoSync()
delete deviceInfoObj.appName
deviceInfo = JSON.stringify(deviceInfoObj)
os = deviceInfoObj.platform
}
const header = {
// 'content-type': contentType,
// H5 方式 token 存在 cookie 的 admin-token 中因为需要跨项目共享token智能客服
// #ifndef H5
'Authorization': uni.getStorageSync('auth-token') ?? '',
'cookie': '', // 此处由于APP会自动带上H5的cookie所以APP此处cookie置空
// #endif
'version': CONSTANT.VERSIONNAME,
deviceInfo,
os,
// #ifdef H5 || MP-WEIXIN
'loginType': 'reserveH5',
// #endif
// #ifdef APP-PLUS
'loginType': 'app',
// #endif
}
// if(option.header) {
// Object.assign(header, option.header);
// }
return new Promise((resolve, reject) => {
uni.uploadFile({
url: _config.api(url),
filePath,
header,
name: 'file',
// formData: {
// projectname: 'app'
// },
success: function(res) {
// _fn.success(resolve, reject, res);
resolve(res);
},
fail: function(res) {
// _fn.fail(resolve, reject, res);
reject(res);
}
});
})
}
export {
request,
upload,
_config
}