ts_aimz/net/http.js
itgaojian163 fb54447a91 优化Net
2025-06-05 17:21:24 +08:00

82 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const Cache = require('../utils/storage');
import {
operatorUrl,
operatorPlug,
uploadImgUrl,
previewUrl,
copyrightUrl,
aiShopUrl,
imgAssets,
appUrl
} from '../net/mainUrl'
// 项目与基础URL映射关系
const PROJECT_URL_MAP = {
operator: operatorUrl,
copyright: copyrightUrl,
plug: operatorPlug,
aiShop: aiShopUrl,
// 添加新项目只需在此扩展
};
/**
* 传入请求参数返回Promise支持链试调用
* @param url 请求地址
* @param method 请求方法类型,不传入默认是"GET"
* @param data 请求体数据
* @param params 请求参数
*/
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"
};
if (needToken) {
const token = Cache.get('token');
if (token) {
headers.Auth = `Bearer ${token}`;
}
}
// 3. 请求配置
const requestConfig = {
url: requestUrl.toString(),
method: method.toUpperCase(),
data,
header: headers,
timeout: 10000,
dataType: "json"
};
return new Promise(function (resolve, reject) {
wx.request({
...requestConfig,
success(res) {
if (res.statusCode === 200) {
resolve(res.data)
} else {
console.log('错误success')
reject(res.data)
}
},
fail(err) {
console.log('错误')
if (err.data) {
reject(err.data)
} else {
reject(err)
}
}
})
})
}
// 导出请求和服务地址
export {
request,
uploadImgUrl,
previewUrl,
copyrightUrl,
imgAssets,
appUrl
}