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

Taro 网络 API 详解与实用案例

Taro 网络 API 详解与实用案例

在现代前端开发中,网络通信是不可或缺的一环。Taro 作为一款多端开发框架,提供了丰富且统一的网络 API,帮助开发者在小程序、H5、React Native 等多端环境下高效地进行数据交互。本文将详细介绍 Taro 的四大网络 API:Taro.requestTaro.uploadFileTaro.downloadFileTaro.connectSocket,并结合实际案例,助你快速掌握其用法。


1. Taro.request(options):发起网络请求

功能说明

Taro.request 是 Taro 提供的通用网络请求方法,支持 GET、POST、PUT、DELETE 等 HTTP 请求方式。它的用法与微信小程序的 wx.request 类似,但可跨端使用。

常用参数

  • url:请求地址(必填)
  • method:请求方法(默认 GET)
  • data:请求参数
  • header:请求头
  • timeout:超时时间(单位 ms)
  • success / fail / complete:回调函数(推荐使用 Promise)

案例

import Taro from '@tarojs/taro'
import { Button, View, Text } from '@tarojs/components'
import { useState } from 'react'export default function RequestDemo() {const [result, setResult] = useState('')const handleRequest = () => {Taro.request({url: 'https://jsonplaceholder.typicode.com/posts/1',method: 'GET'}).then(res => {setResult(JSON.stringify(res.data, null, 2))Taro.showToast({ title: '请求成功', icon: 'success' })}).catch(() => {Taro.showToast({ title: '请求失败', icon: 'none' })})}return (<View><Button onClick={handleRequest}>发起 GET 请求</Button><Text selectable>{result}</Text></View>)
}

2. Taro.uploadFile(options):上传文件

功能说明

Taro.uploadFile 用于将本地资源(如图片、视频等)上传到服务器。常用于用户头像上传、图片发布等场景。

常用参数

  • url:上传接口地址(必填)
  • filePath:要上传的文件路径(必填)
  • name:文件对应的 key,后端通过这个字段获取文件内容(必填)
  • formData:额外的表单数据
  • header:请求头

案例

import Taro from '@tarojs/taro'
import { Button, View, Text } from '@tarojs/components'
import { useState } from 'react'export default function UploadDemo() {const [uploadRes, setUploadRes] = useState('')const handleUpload = () => {Taro.chooseImage({count: 1,success: function (chooseRes) {const tempFilePath = chooseRes.tempFilePaths[0]Taro.uploadFile({url: 'https://httpbin.org/post', // 示例接口filePath: tempFilePath,name: 'file',formData: { user: 'test' },success: function (res) {setUploadRes(res.data)Taro.showToast({ title: '上传成功', icon: 'success' })},fail: function () {Taro.showToast({ title: '上传失败', icon: 'none' })}})}})}return (<View><Button onClick={handleUpload}>选择图片并上传</Button><Text selectable>{uploadRes}</Text></View>)
}

3. Taro.downloadFile(options):下载文件

功能说明

Taro.downloadFile 用于从服务器下载文件到本地。常用于下载图片、文档、音视频等资源。

常用参数

  • url:文件下载地址(必填)
  • header:请求头
  • success / fail / complete:回调函数

案例

import Taro from '@tarojs/taro'
import { Button, View, Text, Image } from '@tarojs/components'
import { useState } from 'react'export default function DownloadDemo() {const [filePath, setFilePath] = useState('')const handleDownload = () => {Taro.downloadFile({url: 'https://img.shields.io/badge/Taro-多端开发-blue.svg',success: function (res) {if (res.statusCode === 200) {setFilePath(res.tempFilePath)Taro.showToast({ title: '下载成功', icon: 'success' })}},fail: function () {Taro.showToast({ title: '下载失败', icon: 'none' })}})}return (<View><Button onClick={handleDownload}>下载图片</Button>{filePath && <Image src={filePath} style={{ width: '200px', height: '60px' }} />}</View>)
}

4. Taro.connectSocket(options):创建 WebSocket 连接

功能说明

Taro.connectSocket 用于创建 WebSocket 连接,实现客户端与服务器的实时通信。适用于聊天、实时数据推送等场景。

常用参数

  • url:WebSocket 服务端地址(必填)
  • header:请求头
  • protocols:子协议数组
  • success / fail / complete:回调函数

案例

import Taro from '@tarojs/taro'
import { Button, View, Text, Input } from '@tarojs/components'
import { useState, useRef } from 'react'export default function WebSocketDemo() {const [msg, setMsg] = useState('')const [log, setLog] = useState([])const socketTaskRef = useRef(null)const connect = () => {const socketTask = Taro.connectSocket({url: 'wss://echo.websocket.org', // 测试 WebSocket 服务success: () => {setLog(l => [...l, 'WebSocket 连接成功'])}})socketTask.onMessage(res => {setLog(l => [...l, '收到消息: ' + res.data])})socketTask.onOpen(() => {setLog(l => [...l, 'WebSocket 已打开'])})socketTask.onClose(() => {setLog(l => [...l, 'WebSocket 已关闭'])})socketTaskRef.current = socketTask}const sendMsg = () => {if (socketTaskRef.current) {socketTaskRef.current.send({ data: msg })setLog(l => [...l, '发送消息: ' + msg])setMsg('')}}const close = () => {if (socketTaskRef.current) {socketTaskRef.current.close()}}return (<View><Button onClick={connect}>连接 WebSocket</Button><Input value={msg} onInput={e => setMsg(e.detail.value)} placeholder="输入消息" /><Button onClick={sendMsg}>发送消息</Button><Button onClick={close}>关闭连接</Button><View>{log.map((item, idx) => <Text key={idx}>{item}{'\n'}</Text>)}</View></View>)
}

推荐阅读:

  • Taro 官方文档 - 网络 API
http://www.lryc.cn/news/596463.html

相关文章:

  • 闲庭信步使用图像验证平台加速FPGA的开发:第三十课——车牌识别的FPGA实现(2)实现车牌定位
  • STM32-第十节-DMA直接存储器存取
  • Collection接口的详细介绍以及底层原理——包括数据结构红黑树、二叉树等,从0到彻底掌握Collection只需这篇文章
  • Class10简洁实现
  • IDEA-自动格式化代码
  • 嵌入式 Qt 开发:实现开机 Logo 和无操作自动锁屏
  • C语言面向对象编程
  • linux 环境服务发生文件句柄泄漏导致服务不可用
  • 自定义HAProxy 错误界面
  • 开发板系统烧写
  • 【数学建模|Matlab】Matlab「基础知识」和「基础操作」
  • Vue3 面试题及详细答案120道(31-45 )
  • Arraylist与LinkedList区别
  • MATLAB软件使用频繁,企业如何做到“少买多用”?
  • 论文略读:Towards Safer Large Language Models through Machine Unlearning
  • Go 的第一类对象与闭包
  • (二)Python基础入门-基础语法核心
  • 【Python】常见模块及其用法
  • 解决栅格数据裁剪矢量数据问题两种方法,ArcGIS解决与PYTHON解决
  • Leetcode力扣解题记录--第41题(原地哈希)
  • 力扣-300.最长递增子序列
  • LeetCode 633.平方数之和
  • Uni-App:跨平台开发的终极解决方案
  • uniapp app打包流程
  • 《Uniapp-Vue 3-TS 实战开发》自定义预约时间段组件
  • Java (Spring AI) 实现MCP server实现数据库的智能问答
  • MS523NA非接触式读卡器 IC
  • 【金融机器学习】第四章:风险-收益权衡——Bryan Kelly, 修大成(中文翻译)
  • 【方案】网页由微应用拼图,微前端
  • Node.js:RESPful API、多进程