HBuilderX uniapp+vue3+vite axios封装

uniapp 封装axios

注:axios必须低于0.26.0,重中之重

重点:封装axios的适配器adapter

1.安装axios

复制代码
npm install axios@0.26.0

创建api文件夹

2.新建adapter.js文件

复制代码
import settle from "axios/lib/core/settle"
import buildURL from "axios/lib/helpers/buildURL"
import buildFullPath from "axios/lib/core/buildFullPath"

const adapter = function(config) {
	return new Promise((resolve, reject) => {

		let fullurl = buildFullPath(config.baseURL, config.url)
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(fullurl, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};

				settle(resolve, reject, response);
			}
		})
	})
}

export default adapter

3.新建index.js文件

复制代码
import axios from "axios";
import adapter from "./adapter"

// 存储请求中的接口
const pending = [];
const instance = axios.create({
	timeout: 60000,
	headers: {
		"Content-Type": "application/json",
	},
});
// 封装的是适配器
instance.defaults.adapter = adapter;
/*
 * 增加请求拦截器
 */
instance.interceptors.request.use(
	config => {
	},
	(error) => {
		/
	}
);
/*
 * 增加响应拦截器
 */
instance.interceptors.response.use(
	(response) => {
	},
	(error) => {
	}
);

export default instance;


export const request = url => {
	return {
		
	};
};

解决问题请双击66666

相关推荐
梦曦i12 小时前
uni-router v0.2.0重磅发布:全链路拦截+重复导航优化
前端·uni-app
EatFan12 小时前
【实战经验】uni-app使用 SSE 踩坑,EventSource不支持怎么办?
android·后端·ios·uni-app
凡泰AI18 小时前
如何为政务 APP 搭建开放平台,实现多部门、第三方供应商标准化入驻与统一管理
android·大数据·小程序·uni-app·app·政务
梦曦i1 天前
@meng-xi/uni-router 未来展望:夯实基础、深化体验、探索前沿
前端·uni-app
2501_916007472 天前
使用Apple Dashboards显示和自定iOS应用性能指标与数据可视化指南
android·ios·小程序·https·uni-app·iphone·webview
爱折腾的编程老炮2 天前
潮玩小程序订单模型-一张表装下所有玩法
spring boot·小程序·uni-app
两个人的幸福online2 天前
UniApp 对接 IM 即时通讯全攻略(下篇)
uni-app
2501_915106322 天前
Flutter iOS混淆打包详细教程与步骤
android·flutter·ios·小程序·uni-app·iphone·webview
DK185838322522 天前
【源码开源部署】电竞代练护航陪玩小程序:全游戏服务平台完整解决方案(附宝塔部署教程)
游戏·微信小程序·uni-app·开源·php
码云数智-大飞2 天前
2026 年跨端开发决战:小程序原生 vs uni-app vs Taro 深度对比
小程序·uni-app·taro