一、创建utils/api.js
const host = ‘http://……‘
/**
* 封装微信的request
* form: ‘application/x-www-form-urlencoded‘
*/
function request(url, data = {}, method = "GET", contentType = ‘json‘) {
return new Promise(function(resolve, reject) {
wx.request({
url: host+url,
data: data,
method: method,
header: {
‘Content-Type‘: contentType.toLowerCase() == ‘json‘ ? "application/json" : "application/x-www-form-urlencoded"
},
success: function(res) {
if (res.statusCode == 200) {
resolve(res.data);
} else {
reject(res.errMsg);
}
},
fail: function(err) {
reject(err)
}
})
});
}
module.exports = {
request: request
}
二、引入
const api = require(‘../../utils/api.js‘)
三、使用
api.request(‘接口‘, {
openId: App.globalData.openId,
id: this.data.id
}, "POST", ‘form‘).then(res => {
if (res.code === 0) {
wx.showToast({
title: ‘成功‘,
icon: ‘none‘
})
}
})