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/

第一种

html 复制代码
<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>

第二种

html 复制代码
<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>

第三种

异步同步化

html 复制代码
<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>

示例:

html 复制代码
<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'; 导入是因为下载了插件(具体可查看博客),没有下载的需常规导入)

运行结果:

相关推荐
颜进强2 分钟前
微信小微AI-接入模式与开通准备|两种模式选错,后面全白干——小微接入的隐藏门槛
前端·ai编程·全栈
htzyl2065 分钟前
CSS中,`:has()` 能帮你删掉的 4 类 JS
前端·css
AI前端工程狮8 分钟前
我把 MCP 长任务拆成三个工具,token 账单涨了 7 倍
javascript·人工智能·程序员
verohh10 分钟前
(四)配置驱动与动态渲染——从固定页面到可组合的前端架构
前端
颜进强14 分钟前
认识小微|一句话就能直接调起你小程序的微信 AI,多数人第一眼就理解错了
前端·ai编程·全栈
锐影用AI做小程序21 分钟前
uni-app X + Spring Boot 做在线工具站:6 个真实踩坑与解法
前端
掘金挖土21 分钟前
前端手摸手跑路之 AI 应用开发(十二)
前端·后端
颜进强22 分钟前
微信里冒出一个新 AI 入口,我们把接入它的每一步坑都写下来了
前端·ai编程
不要试图纠正别人22 分钟前
178 个 IPC 通道不可怕,可怕的是 preload 里那一行
前端·electron
bai27325 分钟前
Node 22 里的等待:从回调到 Promise,一次上传流程的最小记录
前端