ts_aimz/net/http.js

82 lines
2.0 KiB
JavaScript
Raw Normal View History

2025-03-28 18:36:17 +08:00
const Cache = require('../utils/storage');
import {
operatorUrl,
operatorPlug,
uploadImgUrl,
previewUrl,
copyrightUrl,
2025-06-05 17:21:24 +08:00
aiShopUrl,
2025-05-06 14:04:00 +08:00
imgAssets,
appUrl
} from '../net/mainUrl'
2025-06-05 17:21:24 +08:00
// 项目与基础URL映射关系
const PROJECT_URL_MAP = {
operator: operatorUrl,
copyright: copyrightUrl,
plug: operatorPlug,
aiShop: aiShopUrl,
// 添加新项目只需在此扩展
};
2025-03-21 09:02:29 +08:00
/**
* 传入请求参数返回Promise支持链试调用
* @param url 请求地址
* @param method 请求方法类型不传入默认是"GET"
* @param data 请求体数据
* @param params 请求参数
*/
2025-06-05 17:21:24 +08:00
function request(url, method = "GET", data = {}, project = "copyright", needToken = true) {
// 1. 参数预处理
const baseUrl = PROJECT_URL_MAP[project] || copyrightUrl;
const requestUrl = baseUrl + url;
// 2. 请求头配置
const headers = {
"Content-Type": "application/json"
};
2025-03-28 18:36:17 +08:00
if (needToken) {
2025-06-05 17:21:24 +08:00
const token = Cache.get('token');
2025-03-28 18:36:17 +08:00
if (token) {
2025-06-05 17:21:24 +08:00
headers.Auth = `Bearer ${token}`;
2025-03-28 18:36:17 +08:00
}
}
2025-06-05 17:21:24 +08:00
// 3. 请求配置
const requestConfig = {
url: requestUrl.toString(),
method: method.toUpperCase(),
data,
header: headers,
timeout: 10000,
dataType: "json"
};
2025-03-21 09:02:29 +08:00
return new Promise(function (resolve, reject) {
wx.request({
2025-06-05 17:21:24 +08:00
...requestConfig,
2025-03-21 09:02:29 +08:00
success(res) {
if (res.statusCode === 200) {
resolve(res.data)
} else {
2025-04-03 10:44:12 +08:00
console.log('错误success')
reject(res.data)
2025-03-21 09:02:29 +08:00
}
},
fail(err) {
2025-04-03 10:44:12 +08:00
console.log('错误')
if (err.data) {
reject(err.data)
} else {
reject(err)
}
2025-03-21 09:02:29 +08:00
}
})
})
}
// 导出请求和服务地址
export {
2025-03-31 18:23:29 +08:00
request,
2025-04-03 10:44:12 +08:00
uploadImgUrl,
previewUrl,
copyrightUrl,
2025-05-06 14:04:00 +08:00
imgAssets,
appUrl
2025-03-21 09:02:29 +08:00
}