> 技术文档 > Taro 网络 API 详解与实用案例

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 (   {result}  )}

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 (   {uploadRes}  )}

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 (   {filePath && <Image src={filePath} style={{ width: \'200px\', height: \'60px\' }} />}  )}

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 (    setMsg(e.detail.value)} placeholder=\"输入消息\" />    {log.map((item, idx) => {item}{\'\\n\'})}   )}

推荐阅读:

  • Taro 官方文档 - 网络 API