如何在Taro项目中使用axios

Axios 默认使用 XMLHttpRequestNode.jshttp 模块,这在某些小程序端可能不支持:

  • H5 端:完全支持
  • React Native 端:需要配置适配器
  • 微信/支付宝等小程序端不支持 (因为小程序环境没有 XMLHttpRequest

对于需要在多端使用 Axios 的项目,可以配置适配器:

bash 复制代码
pnpm install axios @tarojs/taro
js 复制代码
// utils/axiosAdapter.js
import axios from 'axios'
import Taro from '@tarojs/taro'

// 创建自定义适配器
const taroAdapter = (config) => {
  return new Promise((resolve, reject) => {
    Taro.request({
      url: config.url,
      method: config.method?.toUpperCase() || 'GET',
      data: config.data || config.params,
      header: config.headers,
      success: (response) => {
        resolve({
          data: response.data,
          status: response.statusCode,
          statusText: 'OK',
          headers: response.header,
          config: config,
          request: null
        })
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}

// 创建 Axios 实例
const instance = axios.create({
  adapter: taroAdapter,
  baseURL: 'https://api.example.com',
  timeout: 10000,
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 添加 token
    const token = Taro.getStorageSync('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    // 统一错误处理
    Taro.showToast({
      title: '请求失败',
      icon: 'error'
    })
    return Promise.reject(error)
  }
)

export default instance
相关推荐
WangHappy15 小时前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端20 小时前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
icebreaker2 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker2 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
大米饭消灭者4 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
FliPPeDround6 天前
Vitest Environment UniApp:让 uni-app E2E 测试变得前所未有的简单
微信小程序·e2e·前端工程化
FliPPeDround6 天前
微信小程序自动化的 AI 新时代:wechat-devtools-mcp 智能方案
微信小程序·ai编程·mcp
码云数智-大飞6 天前
如何创建自己的小程序,码云数智与有赞平台对比
微信小程序
luffy54596 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序
Slow菜鸟6 天前
微信小程序开发(二)目录结构完全指南
微信小程序·小程序