微信小程序请求封装
requers.js
/**
* Promise封装微信请求
*/
function request(url, method, data, contentType = 'json', host) {
contentType === 'form' && (contentType = 'application/x-www-form-urlencoded')
contentType === 'json' && (contentType = 'application/json; charset=utf-8')
contentType === 'file' && (contentType = 'multipart/form-data')
let header = {
'Content-Type': contentType,
Authorization: wx.getStorageSync('token')
}
return new Promise((resolve, reject) => {
wx.request({
url: host + url,
method: method,
data: data,
header: header,
timeout: 6000,
success: function (res) {
if (res.statusCode === 401) {
// ...
}
resolve(res.data)
},
fail: function (err) {
reject(err);
}
})
})
}
module.exports = request
api.js
const app = getApp()
import request from './request'
const baseUrl = app.globalData.baseUrl
module.exports = {
common: {
login(params) {
return request('/core/sys/XXXX', 'POST', params, 'form', baseUrl)
},
// ...
},
// ...
}
使用
app.$api.common.login(data).then(res => {
if (res.code === 200) {
}
})