如何在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
相关推荐
2501_933907216 小时前
深圳本凡科技专业企业APP开发,助力手机应用创新优化
科技·微信小程序·小程序
java1234_小锋8 小时前
分享一套优质的微信小程序校园志愿者系统(SpringBoot后端+Vue3管理端)
微信小程序·小程序·校园志愿者
“负拾捌”1 天前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
换日线°2 天前
NFC标签打开微信小程序
前端·微信小程序
光影少年2 天前
AIGC + Taro / 小程序
小程序·aigc·taro
菜鸟una3 天前
【微信小程序+Taro 3+NutUI 3】input (nut-input) 、 textarea (nut-texteare)类型使用避坑
前端·vue.js·微信小程序·小程序·taro
计算机毕设指导63 天前
基于微信小程序的校园二手交易系统【源码文末联系】
java·spring boot·spring·微信小程序·小程序·tomcat·maven
Java.慈祥3 天前
速通-微信小程序 2Day
微信小程序·小程序·前端框架
2501_933907213 天前
宁波小程序公司是什么?主要提供宁波微信小程序制作与服务吗?
科技·微信小程序·小程序
码云数智-大飞3 天前
微信商城小程序怎么弄?2026年主流小程序商城平台对比
微信小程序