由于我的uniapp项目是通过vite脚手架搭建的,当时选择了axios作为请求方式,在本地调试的时候也一直没发现有问题,直到打包成app在真机上登录,发现报错There is no suitable adapter to dispatch the request since:-adapter xhr is not supported by the environment -adapter http is not available in the build -adapter fetch is not supported by the environment;才发现uniapp并不兼容axios。为了解决这个问题,找到了一款axios适配uniapp的插件,使用方法也非常简单。
@uni-helper/axios-adapter
插件地址:https://uni-helper.js.org/axios-adapter
下载
pnpm install @uni-helper/axios-adapter
使用
在你的axios封装方法中,import导入插件,在axios.create里配置适配器adapter即可解决uniapp兼容axios问题。
import axios from 'axios'
import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter'// 配置服务api
const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API ,adapter:createUniAppAxiosAdapter(),timeout: 15000
})//拦截
service.interceptors.request.use(config =>{},error =>{}
)//响应
service.interceptors.response.use(response =>{},error =>{}
)