新建request.js
const baseUrl = 'http://xxx.xxxx.xxx';//接口域名
let reqCount = 0,resCount = 0;//记录请求次数和响应次数
const request = (options) => {
reqCount++;
uni.showLoading();
return new Promise((resolve, reject) => {
uni.request({
method: options.method,
url: baseUrl + options.url,
data: options.data,
header: options.header//如需其他配置可在此添加或先转换options.url,然后 ...options
}).then((response) => {
resCount++
if(reqCount === resCount) uni.hideLoading();//防止连续请求多个接口时loading闪现
let [error, res] = response;
resolve(res.data);
}).catch(error => {
resCount++
if(reqCount === resCount) uni.hideLoading();
let [err, res] = error;
reject(err)
})
});
}
export default request
main.js中:
导入request,并挂载到vue
import request from "utils/request.js"
Vue.prototype.$request = request
在组件中使用:
this.$request({
url:"/xxx/xxx/xxx",
method:"POST",
data:{"id":1}
}).then((res)=>{
console.log(res)
}).catch((error)=>{
console.log(error)
})
网友评论