【微信小程序】HTTP封装与使用示例

config.js

1
2
3
4
5
6
const config = {
api_base_url: 'http://bl.7yue.pro/v1/',
appkey:'AbhC31IG7ruCDp57'
}

export {config}

util/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
import {
config
} from '../config.js'

const tips = {
1: '抱歉,出现了一个错误',
1007: 'url路径错误',
1005: '不正确的开发者key',
3000: '该期内容不存在'
}

class HTTP {
request(params) {
if (!params.method) {
params.method = 'GET'
}
wx.request({
url: config.api_base_url + params.url,
method: params.method,
data: params.data,
header: {
'content-type': 'application/json',
'appkey': config.appkey
},
success: (res) => {
let code = res.statusCode.toString()
if (code.startsWith('2')) {
params.success && params.success(res.data)
} else {
let errorCode = res.data.error_code
this._showError(errorCode)
}
},
fail: (err) => {
this._showError(1)
}
})
}

_showError(errorCode) {
if (!errorCode) {
errorCode = 1
}
wx.showToast({
title: tips[errorCode],
icon: 'none',
duration: 2000
})
}
}

export {
HTTP
}

models/classic.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { HTTP } from '../util/http.js'

class ClassicModel extends HTTP {
constructor() {
super()
}

getLatest(callBack){
this.request({
url:'classic/latest',
success:(data) => {
callBack(data)
}
})
}
}

export {ClassicModel}

models/like.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { HTTP } from '../util/http.js'

class LikeModel extends HTTP {
constructor() {
super()
}

like(behavior, artId, type){
let url = behavior == 'like' ? 'like' : 'like/cancel'
this.request({
url:url,
method: 'POST',
data: {
art_id: artId,
type: type
},
})
}
}

export {LikeModel}

page/classic/classic.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
import {ClassicModel} from '../../models/classic.js'
import {LikeModel} from '../../models/like.js'
let classicModel = new ClassicModel()
let likeModel = new LikeModel()

Page({

/**
* 页面的初始数据
*/
data: {
classicData:null,
first:false,
last:true,
},

/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
classicModel.getLatest((data)=>{
this.setData({
classicData:data
})
})
},

handleLike (e) {
let behavior = e.detail.behavior
likeModel.like(behavior, this.data.classicData.id, this.data.classicData.type)
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {

},

/**
* 生命周期函数--监听页面显示
*/
onShow: function () {

},

/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {

},

/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {

},

/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {

},

/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {

},

/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {

}
})