【UniApp】-uni-app-网络请求 - BNTang
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.
【UniApp】-uni-app-网络请求 - BNTang - 博客园
- 经过上个章节的介绍,大家可以了解到 uni-app-pinia存储数据的基本使用方法
- 那本章节来给大家介绍一下 uni-app-网络请求 的基本使用方法
- 首先我们打开官方文档,我先带着大家看一下官方文档的介绍:https://uniapp.dcloud.net.cn/api/request/request.html
- 从官方文档中我们可以看到,可以通过
uni.request(OBJECT)
来发起网络请求
好,那么废话不多说,我们直接来看一下代码,搭建一个普通模板的项目,自行去搭建,大家都有相关的经验了,我就不多说了。
在首页页面,编写两个按钮分别发送 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
:请求方法,有效值:GET
,POST
,PUT
,DELETE
,CONNECT
,HEAD
,OPTIONS
,TRACE
,UPLOAD
,比较常用的是GET
和POST
header
:自定义请求头信息success
:接口调用成功的回调函数fail
:接口调用失败的回调函数
好,我们来运行一下,看一下效果:
通过如上的示例,我觉得大家唯一有疑问的可能就是这个请求地址了,这个请求地址是我在网上搜索的一个在线的接口,可以用于测试学习使用:
我这里使用的是 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 等等相关的,都是一样的,好了本文就先介绍到这里,下一篇我再来给大家写一个项目(苹果计算器),给这个系列画上一个句号。
- 如果你有任何问题或建议,欢迎在下方留言,我会尽快回复
- 如果你觉得本文对你有帮助,欢迎点赞、收藏,你的支持是我写作的最大动力
__EOF__
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK