quanyawei
2023-10-20 e5f4a463ed9a9af66035f72da8e8aef54a07baad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import storage from "./storage"; // 缓存封装
export default {
  console(options) {
    if (config.debug) {
      console.log("<<===============================================>>");
      // console.log("request start");
      // console.log("header" + JSON.stringify(options.header));
      // console.log("method: " + options.method + " URL: " + options.url);
      // console.log(options.data);
      // console.log("request end");
      // console.log("<<===============================================>>");
    }
  },
  domain() {
    return config.uni_app_web_api_url.replace("api", "");
  },
  send(options = {}, isLogin = true) {
    const baseUrl = process.uniEnv.baseUrl;
    storage.set("baseUrl", baseUrl);
    console.log("baseUrl", process.uniEnv);
    // loading加载
    uni.showLoading({
      title: "加载中",
    });
 
    // 拼接路劲,下面的配置文件会提到
    options.url = baseUrl + "" + options.url;
    // 请求方式
    options.method = options.method || "GET";
    // 判断登录是否
    console.log('isLogin',isLogin)
    if (isLogin) {
      let token = storage.get("token");
      console.log("token", token);
      if (token != null) {
        // options.header["token"] = token;
        options.header = {
          token: token,
          Authorization: token,
        };
      }
    }
    console.log("options", options);
    // this.console(options); // 打印请求数据,调试用,上线可以注释
 
    // 发起Promise请求
    return new Promise((resolve, reject) => {
      uni.request(options).then((data) => {
        console.log("datadatadata", data);
        var [error, res] = data;
        if (error != null) {
          reject(error);
        } else {
          // 相应拦截、根据后端的状态码来写,可以自行判断和封装
          if (res.data.code === 0) {
            uni.hideLoading();
            // uni.navigateTo({
            //   url: "/pages/Login/login/login",
            // });
            resolve(res.data);
          } else {
            uni.hideLoading();
            reject(res.data.message);
          }
        }
      });
    });
  },
  get(url = "", data = {}, isLogin = true) {
    return this.send(
      {
        url: url,
        data: data,
      },
      isLogin
    );
  },
  post(url = "", data = {}, isLogin = true) {
    return this.send(
      {
        url: url,
        data: data,
        method: "POST",
      },
      isLogin
    );
  },
};