3

【UniApp】-uni-app-网络请求 - BNTang

 9 months ago
source link: https://www.cnblogs.com/BNTang/p/17915477.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【UniApp】-uni-app-网络请求 - BNTang - 博客园

2105804-20231203182056274-624091530.png
  • 经过上个章节的介绍,大家可以了解到 uni-app-pinia存储数据的基本使用方法
  • 那本章节来给大家介绍一下 uni-app-网络请求 的基本使用方法

好,那么废话不多说,我们直接来看一下代码,搭建一个普通模板的项目,自行去搭建,大家都有相关的经验了,我就不多说了。

在首页页面,编写两个按钮分别发送 get 请求和 post 请求,代码如下:

<template>
	<view>
		<button type="primary" @click="reqGetFn">发送Get请求</button>
		<button type="primary" @click="reqPostFn">发送Post请求</button>
	</view>
</template>

<script setup>
	function reqGetFn() {
		uni.request({
			url: 'https://jsonplaceholder.typicode.com/posts',
			data: {
				text: 'BNTang'
			},
			method: "GET",
			header: {
				// 自定义请求头信息
				'custom-header': 'hello'
			},
			success: (res) => {
				console.log(res);
				console.log(res.data);
			}
		});
	}

	function reqPostFn() {
		uni.request({
			url: 'https://jsonplaceholder.typicode.com/posts',
			data: {
				text: 'BNTang'
			},
			method: "POST",
			header: {
				// 自定义请求头信息
				'custom-header': 'hello'
			},
			success: (res) => {
				console.log(res);
				console.log(res.data);
			}
		});
	}
</script>
  • 代码中,通过 uni.request(OBJECT) 来发起网络请求,OBJECT 是一个对象,其属性有:
  • url:开发者服务器接口地址
  • data:请求的参数
  • method:请求方法,有效值:GETPOSTPUTDELETECONNECTHEADOPTIONSTRACEUPLOAD,比较常用的是 GETPOST
  • header:自定义请求头信息
  • success:接口调用成功的回调函数
  • fail:接口调用失败的回调函数

好,我们来运行一下,看一下效果:

2105804-20231217173320304-1679916389.gif

通过如上的示例,我觉得大家唯一有疑问的可能就是这个请求地址了,这个请求地址是我在网上搜索的一个在线的接口,可以用于测试学习使用:

2105804-20231217173428812-498029689.png

我这里使用的是 JSON Placeholder:https://jsonplaceholder.typicode.com

封装网络请求

  • 通过如上的示例,我们可以看到,通过 uni.request(OBJECT) 来发起网络请求,是非常简单的,只需要传入相关的参数即可
  • 但是,我们在实际开发中,肯定是需要封装一下的,这样才能更好的使用,那么我们来封装一下

新建一个 tools 文件夹,然后在 tools 文件夹下新建一个 network.js 文件,代码如下:

javascript

class ITRequest{
	request(url, method, data){
		return new Promise((resolve, reject)=>{
			uni.request({
				url: url,
				method: method,
				data: data,
				timeout: 3000,
				success: function(res){
					resolve(res.data);
				},
				fail: function(err){
					reject(err);
				}
			})
		})
	}
	get(url, data){
		this.request(url, "GET", data);
	},
	post(url, data){
		this.request(url, "POST", data);
	},
}

export default new ITRequest();

我封装好了,大家直接用即可非常的简单,因为在之前我也封装过对应原生的与 axios 等等相关的,都是一样的,好了本文就先介绍到这里,下一篇我再来给大家写一个项目(苹果计算器),给这个系列画上一个句号。

  • 如果你有任何问题或建议,欢迎在下方留言,我会尽快回复
  • 如果你觉得本文对你有帮助,欢迎点赞、收藏,你的支持是我写作的最大动力

2105804-20231129232539490-1458223711.png

__EOF__

本文作者: BNTang 本文链接: https://www.cnblogs.com/BNTang/p/17915477.html 关于博主: 评论和私信会在第一时间回复。或者直接私信我。 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处! 声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK