uni-app小程序开发-接口请求

前言

https://uniapp.dcloud.net.cn/api/

封装

工具类

/utils/http.js

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
89
90
class Request {
constructor(options = {}) {
// 请求的根路径
this.baseUrl = options.baseUrl || ''
// 请求的 url 地址
this.url = options.url || ''
// 请求方式
this.method = 'GET'
// 请求的参数对象
this.data = null
// header 请求头
this.header = options.header || {}
this.beforeRequest = null
this.afterRequest = null
}

// 添加对header的支持
_mergeHeaders(customHeader = {}) {
return Object.assign({}, this.header, customHeader); // 合并默认header和自定义header
}

get(url, data = {}) {
this.method = 'GET'
this.url = this.baseUrl + url
this.data = data
return this._()
}

post(url, data = {}, header = {}) {
this.method = 'POST'
this.url = this.baseUrl + url
this.data = data
this.header = this._mergeHeaders(header) // 合并header
return this._()
}

put(url, data = {}) {
this.method = 'PUT'
this.url = this.baseUrl + url
this.data = data
return this._()
}

delete(url, data = {}) {
this.method = 'DELETE'
this.url = this.baseUrl + url
this.data = data
return this._()
}

_() {
// 清空 header 对象
this.header = {}
// 请求之前做一些事
this.beforeRequest && typeof this.beforeRequest === 'function' && this.beforeRequest(this)
// 发起请求
return new Promise((resolve, reject) => {
uni.request({
url: this.url,
method: this.method,
data: this.data,
header: this.header,
success: (res) => {
if (res.statusCode == 200) {
resolve(res.data)
} else {
resolve({
code: 1,
msg: "请求失败"
});
}
},
fail: (err) => {
resolve({
code: 1,
msg: "请求失败"

});
},
complete: (res) => {
// 请求完成以后做一些事情
this.afterRequest && typeof this.afterRequest === 'function' && this
.afterRequest(res)
}
})
})
}
}

export const $http = new Request()

引用

main.js中添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import {
$http
} from './utils/http.js'
uni.$http = $http
// 配置请求根路径
$http.baseUrl = 'https://api.psvmc.cn/'
// 请求开始之前做一些事情
$http.beforeRequest = function(options) {
uni.showLoading({
title: '数据加载中...',
})
}

// 请求完成之后做一些事情
$http.afterRequest = function() {
uni.hideLoading()
}

调用

1
2
3
4
async getStatusInfo() {
const result = await uni.$http.get('/status/info');
console.log(result);
},

或者

1
2
3
4
async getStatusInfo() {
const result = await uni.$http.post('/status/info',{name:'psvmc'});
console.log(result);
},