原生发请求
wx.request({
url: "",
success(res) {
console.log(res);
}
});
uni-app封装的请求(原因是原生请求没有进行promise封装)
使用uni-app的api发送请求
uni
.request({
url: "", //仅为示例,并非真实接口地址。
data: {
text: "uni.request"
},
header: {
"custom-header": "hello" //自定义请求头信息
}
})
.then(res => {
console.log(res);
});
封装自己的异步请求
为什么要封装
- 原生的不支持promise
- uniapp的原生请求如果要加loading效果会很麻烦
- uniapp的请求返回值是一个数组,他的第1项才是返回的信息,第0项返回的错误信息,如果正确就是null
export default params => {
//加载中
uni.showLoading({
title: '加载中'
});
return new Promise((resolve, reject) => {
wx.request({
...params,
success(res) {
resolve(res.data)
},
fail(err) {
reject(err)
},
complete() {
uni.hideLoading()
}
})
})
}
然后挂载到原型上就可以使用了
One comment
niu bi a