quanyawei
2024-06-27 3db69ad0012032cf01c0911d2517135394ec9bea
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
import storage from './storage' // 缓存封装
import store from '../store/index.js'
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)
        // loading加载
        uni.showLoading({
            title: '加载中',
        })
        // 拼接路劲,下面的配置文件会提到
        // uni.showLoading({ title: baseUrl, })
        options.url = baseUrl + '' + options.url
        // 请求方式
        options.method = options.method || 'GET'
        // 判断登录是否
        if (isLogin) {
            let token = uni.getStorageSync('tonken')
            if (token !== null) {
                // options.header["token"] = token;
                options.header = {
                    token: token,
                    Authorization: token,
                }
            }
        }
        // this.console(options); // 打印请求数据,调试用,上线可以注释
        // 发起Promise请求
        return new Promise((resolve, reject) => {
            uni.request(options).then(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)
    },
}