promise封装uniapp中的uni.request

5 篇文章 0 订阅
3 篇文章 0 订阅

简介

在uniapp项目中,封装request请求,来实现代码的重用性。
~
uni.request发包:
常规操作:

uni.request({
					url:"http://www.xxxxxx.com/xxx.php",
					data:{
						username:username,
						passwd:passwd
					},
					header:{
						'content-type': 'application/x-www-form-urlencoded'
					},	
					method:"POST",
					fail: (err) => {
						console.log(err.data);
					},
					success: (e) => {
						console.log(e.data)
						})
						
							

post传参,书写起来很庞大,建议封装,封装的话不好对返回的数据判断和操作,使用ES6中定义好的构造函数Promise来进行封装,
Promise设置好了返回的各种参数。

操作

定义文件 “./common/js/request.js”
在这里插入图片描述

内容如下:

const baseUrl = "http://www.xxxxxx.com";  //在这里输入提供服务的服务器网址

const request = (url='',data={})=>
{
	uni.showLoading({
		title:'请稍候',
	});
	setTimeout(function () {      //自动停止加载
	    uni.hideLoading();
	}, 2000);
	
	return new Promise((resolve,reject)=>{     //返回一个promise对象
		  
		uni.request({
			url:baseUrl+url,     //加上设定的网址
			method:"POST",
			data:data,
			header:{
				'content-type': 'application/x-www-form-urlencoded'   //防止编码问题
				},
			success: (res) => {
				
				uni.hideLoading();
				if(res.statusCode==200){
					resolve(res)   //成功返回
				}
				else{
					resolve({
						data:"请求失败,请检查网络连接",    //返回提示的json数据
						statusCode: 404
						})
				}
				
			},
			fail: (err) => {
				reject(err)  //失败返回
				uni.hideLoading();
			}
		})
	});
		
	
}
export default request    //暴露出来

resolve和reject返回不同情况下的数据,在resolve返回成功的数据中,判断其中的
statusCode是否为200来判断是否连接正常。

调用

在main.js中挂载到全局:

import request from "common/js/request.js"
Vue.prototype.$request=request  

在这里插入图片描述
在主页面,使用this.$request来进行发包:
在method里定义一个函数,test(),通过点击按钮调用

test(){
				this.$request('/xxxx.php', {  
					test:'xxxx'
				}).then((res) =>{	
					console.log(res.data)
				})					
			}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

F1gh4

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值