uniapp---request请求及其封装

前端向后台发送获取数据网络请求,使用uni.request()   https://uniapp.dcloud.io/api/request/request

一、uni.request请求

methods:{
    getData(){
		uni.request({
			url:'https://www.example.com/request', //仅为示例,并非真实接口地址。
            data: {
                text: 'uni.request'
            },
            header: {
                'custom-header': 'hello' //自定义请求头信息
            },
			success:res=> {
			    console.log(res)
			    if(res.data.status!==0){
				    return uni.showToast({
						title:"数据获取失败"
				    })
			    }
			    this.data=res.data.messege
			}
		})
	}
}

二、封装uni.request请求

网络请求一般都会封转成一个公用的工具类,专门处理网络请求。这样集中处理接口地址,清晰、方便且高效。具体如下:

(1)在项目下新建【http】文件夹,新建【api.js】文件

const BASE_URL="http://192.168.34.121:8080"
export const myRequest=(options)=>{
	return new Promise((resolve,reject)=>{
		uni.request({
			url:BASE_URL+options.url,
			method:options.method || 'GET',
			data:options.data || {},
			success:(res)=>{
				resolve(res)
			},
			fail:(err)=>{
				uni.showToast({
					title:"请求接口失败"
				})
				reject(err)
			}
		})
	})
}

(2)在【main.js】将request请求挂在在原型链上(全局使用)

import {myRequest} from "./http/api.js"

// 挂载全局
Vue.prototype.$myRequest=myRequest

(3)在页面或组件中通过【this.$myRequest()】使用封装好的请求接口

methods:{
  saveData(){
	var param={
					cardImage:this.cardImage,
					cardInfo:this.cardInfo,
					type:this.type
				}
				console.log(param)
				this.$myRequest({
					url:"card/save",
					method:"POST",
					data:param
				}).then(res=>{
					console.log(res)
					if(res.data.respCode=="00000"){}else{}
					uni.showToast({title:res.data.respDesc,icon:"none"})
					uni.navigateTo({
						url:"/pages/index/index"
					})
				}).catch(err=>{
					console.log(err)
				})
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值