如何在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
相关推荐
FinClip6 小时前
微信AI小程序“亿元计划”来了!你的APP如何一键接入,抢先变现?
前端·微信小程序·app
计算机毕设指导611 小时前
基于微信小程序的考研资源共享系统【源码文末联系】
java·spring boot·后端·考研·微信小程序·小程序·maven
沉默-_-11 小时前
从小程序前端到Spring后端:新手上路必须理清的核心概念图
java·前端·后端·spring·微信小程序
week_泽11 小时前
百战商城商品数据云函数化改造总结_百战_3
数据库·笔记·微信小程序·小程序
『 时光荏苒 』12 小时前
微信小程序we分析如何采集webview的体验信息
微信小程序·小程序·webview·we分析
百锦再12 小时前
Vue大屏开发全流程及技术细节详解
前端·javascript·vue.js·微信小程序·小程序·架构·ecmascript
项目題供诗13 小时前
微信小程序黑马优购(项目)(十五)
微信小程序·小程序
云起SAAS13 小时前
婚礼邀请函请柬请帖制作生成抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·婚礼邀请函
毕设源码-邱学长14 小时前
【开题答辩全过程】以 旅游信息系统为例,包含答辩的问题和答案
学习·微信小程序·小程序
计算机毕设指导614 小时前
基于微信小程序的直播带货商品数据分析系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea