Taro 網絡 API 詳解與實用案例
在現代前端開發中,網絡通信是不可或缺的一環。Taro 作為一款多端開發框架,提供了豐富且統一的網絡 API,幫助開發者在小程序、H5、React Native 等多端環境下高效地進行數據交互。本文將詳細介紹 Taro 的四大網絡 API:Taro.request
、Taro.uploadFile
、Taro.downloadFile
和 Taro.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