微信小程序wx.request封装

1.用 class 定义 request 的getpostputdelete四个常用的查增改删方法, 参数使用和 axios 一样的参数格式。

Request
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
class Request {
constructor(parms) {
this.withBaseURL = parms.withBaseURL;
this.baseURL = parms.baseURL;
}
get(url, data, customParams) {
return this.request("GET", url, data, customParams);
}
post(url, data, customParams) {
return this.request("POST", url, data, customParams);
}
put(url, data, customParams) {
return this.request("PUT", url, data, customParams);
}
delete(url, data, customParams) {
return this.request("DELETE", url, data, customParams);
}
request(method, url, data, customParams = {}) {
const vm = this;
const withBaseURL = _.startsWith(url, "http") ? false : vm.withBaseURL;
return new Promise((resolve, reject) => {
wx.request({
url: withBaseURL ? vm.baseURL + url : url,
data,
method,
header: {
Cookie: wx.getStorageSync("Cookie"),
},
...customParams,
success(res) {
setCookie(res);
const statusCode = res.statusCode;
if (statusCode !== 200) {
reject({
statusCode: statusCode,
msg: "请求失败",
url: withBaseURL ? vm.baseURL + url : url,
method,
data,
err: _.get(res, "data"),
});
} else {
resolve(res);
}
},
fail(err) {
reject({
msg: "请求失败",
url: vm.withBaseURL ? vm.baseURL + url : url,
method,
data,
err: err,
});
},
});
});
}
}
  1. 在/utils/utils.js(名字和路径可以随意,只要用的时候 require 对应的 js 文件就可以)导出封装完毕的commonRequest(名字随意)方法
export custom request method
1
2
3
4
5
6
7
8
const commonRequest = new Request({
baseURL: commonApiUrl,
withBaseURL: true,
});

module.exports = {
commonRequest,
};
  1. 在你的 js 中使用commonRequest
use your custom request
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const utils = require("/utils/utils.js");

Component({
data: {
result: null,
},
ready() {
this.getData();
},
methods: {
getData() {
utils.commonRequest
.get("/api/getsomedata")
.then((res) => {
this.setData({
result: res.data,
});
})
.catch((err) => {
// handle your err
});
},
},
});

配合另一篇文章的 setCookie 使用。

完整的 utils.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const _ = require("./lodash");

class Request {
constructor(parms) {
this.withBaseURL = parms.withBaseURL;
this.baseURL = parms.baseURL;
}
get(url, data, customParams) {
return this.request("GET", url, data, customParams);
}
post(url, data, customParams) {
return this.request("POST", url, data, customParams);
}
put(url, data, customParams) {
return this.request("PUT", url, data, customParams);
}
delete(url, data, customParams) {
return this.request("DELETE", url, data, customParams);
}
request(method, url, data, customParams = {}) {
const vm = this;
const withBaseURL = _.startsWith(url, "http") ? false : vm.withBaseURL;
return new Promise((resolve, reject) => {
wx.request({
url: withBaseURL ? vm.baseURL + url : url,
data,
method,
header: {
Cookie: wx.getStorageSync("Cookie"),
},
// customParams这里放自定义的request额外参数,默认为空
...customParams,
success(res) {
setCookie(res);
const statusCode = res.statusCode;
if (statusCode !== 200) {
reject({
statusCode: statusCode,
msg: "请求失败",
url: withBaseURL ? vm.baseURL + url : url,
method,
data,
err: _.get(res, "data"),
});
} else {
resolve(res);
}
},
fail(err) {
reject({
msg: "请求失败",
url: vm.withBaseURL ? vm.baseURL + url : url,
method,
data,
err: err,
});
},
});
});
}
}

const mode = "dev";

const apiUrl = `https://${mode === "prod" ? "" : mode}api.yoursite.com`;

const commonRequest = new Request({
baseURL: apiUrl,
withBaseURL: true,
});

const setCookie = (data) => {
let cookieArr = [];
if (_.get(data, `header['Set-Cookie']`)) {
const cookieOriArr =
data.header["Set-Cookie"].match(/([\w\-.]*)=([^\s=]+);/g) || [];
_.forEach(cookieOriArr, (str) => {
if (!/path=|domain=|samesite=|max-age=/gi.test(str)) {
cookieArr.push(
_.endsWith(str, ";") ? str.substring(0, str.length - 1) : str
);
}
});

let localCookie = wx.getStorageSync("Cookie") || "";
let CookieObj = {};
const localCookieArr = localCookie.split(";") || [];

_.forEach(_.compact(localCookieArr), (item) => {
const cookieItem = item.split("=");
CookieObj[cookieItem[0]] = cookieItem[1];
});

_.forEach(_.compact(cookieArr), (item) => {
const cookieItem = item.split("=");
CookieObj[cookieItem[0]] = cookieItem[1];
});

const CookieStr = _.map(_.keys(CookieObj), (key) => {
return `${key}=${CookieObj[key]}`;
}).join(";");
wx.setStorageSync("Cookie", CookieStr);
}
};

module.exports = {
commonRequest,
setCookie,
};

微信小程序wx.request封装

https://lynan.cn/use-wx-request-as-promise/

Author

Lynan

Posted on

2020-10-23

Updated on

2023-12-11

Licensed under