data 参数说明
最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:
对于 GET 方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…);
对于 POST 方法且 header[‘content-type’] 为 application/json 的数据,会对数据进行 JSON 序列化;
对于 POST 方法且 header[‘content-type’] 为 application/x-www-form-urlencoded 的数据,会将数据转换成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…);
默认是application/json
,如果使用method: ‘GET’,会自动将
以上是理论格式,实现代码↓↓:
// post请求的特殊处理
//data的格式为JSON对象,如:data={a:1,b:2}
let url, data, contentType='application/json', method='POST' //参数
if (method.toLocaleUpperCase() == 'POST') {
data = util.qs(option.data)
contentType = 'application/x-www-form-urlencoded'
}
wx.request({
url,
method,
data,
header: {
'content-type': contentType
},
success(response) {
// 接口调用成功
resolve(response.data)
},
fail(error) {
// 接口调用失败
reject(error)
},
complete(response) {
// 接口调用结束
}
})
// post请求参数格式转换函数
const qs = obj => {
let arr = [];
for (var o in obj) {
arr.push(encodeURIComponent(o) + "=" + encodeURIComponent(obj[o]));
}
return arr.join("&");
}