ts_aimz/net/http.js

88 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

2025-03-28 18:36:17 +08:00
const Cache = require('../utils/storage');
import {
operatorUrl,
operatorPlug,
uploadImgUrl,
previewUrl,
copyrightUrl,
2025-05-06 14:04:00 +08:00
imgAssets,
appUrl
} from '../net/mainUrl'
2025-03-21 09:02:29 +08:00
/**
* 传入请求参数返回Promise支持链试调用
* @param url 请求地址
* @param method 请求方法类型不传入默认是"GET"
* @param data 请求体数据
* @param params 请求参数
*/
2025-03-28 18:36:17 +08:00
function request(url, method = "GET", data = {}, params = {}, project = "copyright", needToken = true) {
2025-03-21 09:02:29 +08:00
const header = {
"content-type": "application/json"
// 有其他content-type需求加点逻辑判断处理即可
}
2025-03-28 18:36:17 +08:00
//是否需要token
if (needToken) {
const token = Cache.get('token')
if (token) {
header.Auth = `Bearer ${token}`;
}
}
//判断项目
var baseUrl = operatorUrl
if (project == 'operator') {
baseUrl = operatorUrl
} else if (project == 'copyright') {
baseUrl = copyrightUrl
2025-04-27 18:07:06 +08:00
} else if (project == 'plug') {
baseUrl = operatorPlug
2025-03-28 18:36:17 +08:00
}
2025-03-21 09:02:29 +08:00
return new Promise(function (resolve, reject) {
wx.request({
url: baseUrl + url,
timeout: 8000,
method,
data,
dataType: "json", // 微信官方文档中介绍会对数据进行一次JSON.parse
header,
success(res) {
// wx.hideLoading();
// HTTP状态码为200才视为成功
if (res.statusCode === 200) {
// 真正的数据响应体中还有一层success字段判断业务状态按实际情况处理
resolve(res.data)
// if (res.data.success) {
// resolve(res.data.result)
// } else {
// // 业务判断错误
// reject(res)
// }
} else {
2025-04-03 10:44:12 +08:00
console.log('错误success')
2025-03-21 09:02:29 +08:00
// wx.request的特性只要有响应就会走success回调所以在这里判断状态非200的均视为请求失败
2025-04-03 10:44:12 +08:00
reject(res.data)
2025-03-21 09:02:29 +08:00
}
},
fail(err) {
// wx.hideLoading();
// 断网、服务器挂了都会fail回调直接reject即可
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
}