如何在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
相关推荐
自然 醒1 天前
uni-app开发微信小程序,如何使用towxml去渲染md格式和html标签格式的内容?
微信小程序·uni-app·html
竟未曾年少轻狂1 天前
微信小程序-组件开发
微信小程序·小程序
想七想八不如114081 天前
【GitHub开源】一款极简跨平台 Todo 应用:微信小程序 + Windows 桌面挂件 + 实时同步
微信小程序·开源·github
喵了几个咪1 天前
Headless 架构优势:内容与展示解耦,一套 API 打通全端生态
vue.js·架构·golang·cms·react·taro·headless
笨笨狗吞噬者1 天前
代理的妙用:uni-app 小程序是怎样用 `Proxy` 和 `wrapper` 抹平平台差异的
前端·微信小程序·uni-app
px不是xp2 天前
微信小程序组件化开发最佳实践
微信小程序·小程序·notepad++
曲江涛2 天前
微信小程序 摄像头 授权同页面丝滑调用
微信小程序
code_Bo2 天前
kiro生成小程序商业案例
前端·微信小程序·小程序·云开发
克里斯蒂亚诺更新2 天前
微信小程序引入vant weapp,button宽度100%
微信小程序·小程序
nhc0883 天前
贵阳纳海川·花卉游戏行业解决方案
人工智能·游戏·微信小程序·软件开发·小程序开发