在wepy框架中 使用promise对发送网络请求进行封装 包括post跟get请求
// ====utils.js
//==封装post请求
const post = (url,data) =>{
let promise = new Promise((resolve,reject)=>{
wepy.request({
url: url,
data: data,
header:{'content-type':'applicction/x-www-form-urlencoded'} 或者是 header{'content-type':'application/json'},
success: res=>{
if(res.statusCode ==200){
resolve(res)
}else {
reiect(res)
}
},
fail: res=>{
reject(res)
}
})
})
return promise
}
//====封装get请求
const get =(url,data)=>{
let promise = new Promise((resolve,reject)=>{
wepy.request({
url: url,
data: data,
header: {'content-type': 'application/x-www-form-urlencoded'} 或者是 header: {'content-type': 'application/json'},
success: res=>{
if(res.statusCode ==200){
resolve(res)
}else {
reject(res)
}
},
fail: res=>{
reject(res)
}
})
})
return promise
}
module.exports = {
post: post,
get: get
}
//=======引用封装的请求
const utils = require('../utils.js')
utils.post(url,data).then(res=>{
console.log(res) //====请求成功后
}).catch(res=>{
console.log(res) //====失败后的返回
})
/// get请求是同理的