httpUtil.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // 请求地址
  2. const getDomain = (uri, type) => {
  3. const app = getApp();
  4. const { serverUrl, fileserverUrl, wechatUrl } = app.globalData;
  5. // 自定义
  6. if (uri.includes("http")) return uri;
  7. // 微信
  8. if (uri.startsWith("/wechat/api")) return wechatUrl + uri;
  9. // 地址前缀
  10. else if (type) return serverUrl + `/ball/${type}/api/` + uri;
  11. // 常规
  12. return serverUrl + "/ball/v1/api/" + uri;
  13. }
  14. export const $api = async (uri, method = 'GET', data, type) => {
  15. // 请求地址
  16. let baseUrl = getDomain(uri, type);
  17. // 处理空数据
  18. data = getFilterNull(data)
  19. return new Promise((resolve, reject) => {
  20. wx.request({
  21. url: `${baseUrl}`,
  22. method,
  23. data,
  24. header: { 'Content-Type': 'application/json' },
  25. success: (res) => toResolve(resolve, res),
  26. error: (e) => toReject(reject, e),
  27. });
  28. });
  29. }
  30. export const $apifile = async (uri, method, data, type) => {
  31. const app = getApp();
  32. const { fileserverUrl, } = app.globalData;
  33. // 请求地址
  34. // let baseUrl = getDomain(uri, type);
  35. return new Promise((resolve, reject) => {
  36. wx.uploadFile({
  37. url: `${fileserverUrl}/${uri}`,
  38. filePath: data,
  39. name: 'file',
  40. formData: {},
  41. success: (res) => toResolve(resolve, res),
  42. error: (err) => toReject(reject, err),
  43. })
  44. });
  45. }
  46. const toResolve = (resolve, result) => {
  47. if (result.statusCode === 200) resolve(result.data);
  48. else {
  49. console.error("请求失败");
  50. }
  51. };
  52. const toReject = (reject, result) => {
  53. console.error(result);
  54. reject(result);
  55. };
  56. const getFilterNull = (data) => {
  57. for (const key in data) {
  58. //data[key] == null || data[key] == ''
  59. if (data[key] == null) delete data[key]
  60. }
  61. return data;
  62. }