当前位置: 首页 > news >正文

uni-app发起网络请求的三种方式

uni.request(OBJECT) 

发起网络请求 

具体参数可查看官方文档uni-app

data:请求的参数;

header:设置请求的 header,header 中不能设置 Referer;

method:请求方法;

timeout:超时时间,单位 ms(默认60000);

dataType:如果设为 json,会对返回的数据进行一次 JSON.parse,非 json 不会进行 JSON.parse;

....

免费测试api接口:https://jsonplaceholder.typicode.com/ 

第一种

<template>

</template>

<script setup>

	function request(){
		uni.request({
			url:"https://jsonplaceholder.typicode.com/posts", //开发者服务器接口地址
			method:"post",   //请求方法
            success:res=>{   //收到开发者服务器成功返回的回调函数
				console.log(res);
			}
		})
	}

	request();

</script>

<style lang="scss" scoped>
     
</style>

第二种

<template>
	
</template>

<script setup>

	function request(){
		uni.request({
			url:"https://jsonplaceholder.typicode.com/posts"
		}).then(res=>{
			arrs.value=res.data
		})
	}
   
	request();

</script>

<style lang="scss" scoped>
	   
</style>

第三种

 异步同步化

<template>
	
</template>

<script setup>

   async function request(){
	   let res = await uni.request({
	   	url:"https://jsonplaceholder.typicode.com/posts"
	   })
	   arrs.value=res.data
   }
	
	request();

</script>

<style lang="scss" scoped>
	   
</style>

示例:

<template>
	<view class="out" v-for="item in arrs">
		<view class="title">{{item.title}}</view>
		<view class="content">{{item.body}}</view>
	</view>
</template>

<script setup>

	let arrs = ref();
	
	function request(){
		uni.request({
			url:"https://jsonplaceholder.typicode.com/posts"
		}).then(res=>{
			arrs.value=res.data
		})
	}
	
	request();
</script>

<style lang="scss" scoped>
	.out{
		padding: 30rpx;
		.title{
			font-size: 40rpx;
		}
		.content{
			margin: 15rpx 0;
			border-bottom: 1px solid #696969;
			color: #696969;
		}
	}       
</style>

( 注:ref 没有使用 import { ref } from 'vue'; 导入是因为下载了插件(具体可查看博客),没有下载的需常规导入) 

 运行结果:

相关文章:

  • 探讨如何加快 C# 双循环的速度效率
  • 【route】route add命令详解
  • 记一次一波三折的众测SRC经历
  • DevOps自动化部署详解:从理念到实践
  • DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方DeepSeek接入)
  • 从零搭建微服务项目Base(第5章——SpringBoot项目LogBack日志配置+Feign使用)
  • 开源AI智能名片2+1链动模式S2B2C商城小程序在社交价值挖掘中的应用与策略研究
  • Linux 网络安全技巧
  • ubuntu网络及软件包管理
  • ​ ​rust学习四、控制语句
  • 无线网络安全配置指南:WPA、WPA2、WPA3及WAPI详解
  • 大数据治理:数字时代的关键密码
  • LabVIEW无刷电机控制器检测系统
  • 计算机网络基础
  • SpringBoot + minio实现分片上传、秒传、续传
  • 账号矩阵玩法:TikTok美区水晶手链如何实现规模化盈利?
  • 代码随想录算法【Day49】
  • 近地面无人机植被定量遥感与生理参数反演
  • javascript语言设计1
  • 【git-hub项目:YOLOs-CPP】本地实现04:项目简化
  • 苹果第二财季营收增长5%,受关税政策影响预计下一财季新增9亿美元成本
  • “五一”假期首日国铁郑州局迎大客流,预计发送旅客逾95万人次
  • 深观察丨从“不建议将导师挂名为第一作者”说开去
  • 笔墨如何“构城”?上海美院城市山水晋京展出
  • “ChatGPT严选”横空出世了,“DeepSeek严选”还要等多久?
  • 中国人民解放军南部战区位南海海域进行例行巡航