如何在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
相关推荐
斯班奇的好朋友阿法法3 小时前
鸿蒙 vs iOS vs 微信小程序:开发平台全面对比
ios·微信小程序·harmonyos
Greg_Zhong2 天前
微信小程序如何关闭:当前渲染模式为webview?
微信小程序·微信小程序渲染引擎·渲染引擎需搭配更高基础库
橘子海全栈攻城狮2 天前
【最新源码】养老院系统管理A013
java·spring boot·后端·web安全·微信小程序
计算机学姐2 天前
基于微信小程序的校园失物招领管理系统【uniapp+springboot+vue】
java·vue.js·spring boot·mysql·信息可视化·微信小程序·uni-app
SkyWalking中文站2 天前
用 SkyWalking 监控微信和支付宝小程序
微信·微信小程序·支付宝
计算机学姐2 天前
基于微信小程序的宠物服务系统【uniapp+springboot+vue】
java·vue.js·spring boot·mysql·微信小程序·uni-app·宠物
Greg_Zhong2 天前
微信小程序中实现自定义多选效果(完整实现及问题记录)
微信小程序·自定义多选控件
独角鲸网络安全实验室3 天前
2026微信小程序抓包全解析:从实操落地到合规风控,解锁前端调试新范式
前端·微信小程序·小程序·抓包·系统代理绕过·https证书严格校验·进程隔离
fix一个write十个3 天前
【uniApp开发】微信小程序 web-view 内嵌 H5 跳转支付踩坑实录
微信小程序·uni-app
棋宣3 天前
微信小程序onShareAppMessage 分享-生命周期函数 在vue3中 组合式函数 hooks中不生效
微信小程序·小程序