uni-app requset请求封装_api封装

文章发布时间:

最后更新时间:

1
2
3
4
5
6
7
8
9
10
11
import Request from '../utils/request.js'
import operate from './operate.js'
let request = new Request().http

export const getemoji = function(data) {
return request({
url: "",//拼接路径
method: "GET",
data: data
})
}
1
2
3
4
5
export default {
//接口
api: ""
}

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
import operate from '../common/operate.js'
// vuex 的使用 详情参考官网 https://uniapp.dcloud.io/vue-vuex
import store from '../store/index.js'

export default class Request {
http(param) {
// 请求参数
var url = param.url,
method = param.method,
header = {},
data = param.data || {},
hideLoading = param.hideLoading || false;

//拼接完整请求地址
var requestUrl = operate.api + url;
console.log(requestUrl)
//拼接完整请求地址(根据环境切换)
// var requestUrl = operate.api() + url;

//请求方式:GET或POST(POST需配置
// header: {'content-type' : "application/x-www-form-urlencoded"},)
if (method) {
method = method.toUpperCase(); //小写改为大写
if (method == "GET") {
header = {
'content-type': "application/x-www-form-urlencoded"
};
} else {
header = {
'content-type': "application/json"
};
}
}

//加载圈
if (!hideLoading) {
uni.showLoading({
title: '加载中...'
});
}

// 返回promise
return new Promise((resolve, reject) => {
// 请求
uni.request({
url: requestUrl,
data: data,
method: method,
header: header,
success: (res) => {
// 判断 请求api 格式是否正确
if (res.statusCode && res.statusCode != 200) {
uni.showToast({
title: "api错误" + res.errMsg,
icon: 'none'
});
return;
}
// 将结果抛出
resolve(res.data)
},
//请求失败
fail: (e) => {
uni.showToast({
title: "" + e.data,
icon: 'none'
});
resolve(e.data);
},
//请求完成
complete() {
//隐藏加载
if (!hideLoading) {
uni.hideLoading();
}
resolve();
return;
}
})
})
}
}