将 wx.request 封装为 promise
2019-05-22 本文已影响1人
侯工
class Request {
constructor (parms) {
this.withBaseURL = parms.withBaseURL
this.baseURL = parms.baseURL
}
get (url, data) {
return this.request('GET', url, data)
}
post (url, data) {
return this.request('POST', url, data, "application/x-www-form-urlencoded")
}
put (url, data) {
return this.request('PUT', url, data)
}
request (method, url, data, conten_type) {
const vm = this
return new Promise((resolve, reject) => {
wx.request({
url: vm.withBaseURL ? vm.baseURL + url : url,
data,
header: {
'content-type': conten_type
},
method,
dataType: 'json',
responseType: 'text',
success (res) {
resolve(res)
},
fail () {
reject({
msg: '请求失败',
url: vm.withBaseURL ? vm.baseURL + url : url,
method,
data
})
}
})
})
}
}
const request = new Request({
baseURL: 'http://test',
withBaseURL: true
})
module.exports = request
使用的时候
const requests = require('/request/request')
requests.request.get('/aaa', {
a: 0,
b: 1
}).then(res => {
console.log(res)
}).catch(e => {
console.log(e)
})