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

相关推荐
Rysxt_14 小时前
uni-app 使用教程:从入门到发布
uni-app
homelook2 天前
uniapp蓝牙demo
uni-app
2501_915909062 天前
手机崩溃日志导出的工程化体系,从系统级诊断到应用行为分析的多工具协同方法
android·ios·智能手机·小程序·uni-app·iphone·webview
郑州光合科技余经理2 天前
技术视角:海外版一站式同城生活服务平台源码解析
java·开发语言·uni-app·php·排序算法·objective-c·生活
wangdaoyin20102 天前
UniApp中使用LivePlayer进行视频或在流媒体播放
uni-app·liveplayer·h5播放视频
2501_915106322 天前
App HTTPS 抓包实战解析,从代理调试到真实网络流量观察的完整抓包思路
网络协议·http·ios·小程序·https·uni-app·iphone
游戏开发爱好者83 天前
苹果App Store应用程序上架方式全面指南
android·小程序·https·uni-app·iphone·webview
2501_916008893 天前
深入理解 iPhone 文件管理,从沙盒结构到开发调试的多工具协同实践
android·ios·小程序·https·uni-app·iphone·webview
一室易安3 天前
解决使用 UniApp 搭配 Vue3 小程序开始 使用uview-plus 的返回顶部up-back-top中onPageScroll 不触发的问题
小程序·uni-app
yilan_n3 天前
鸿蒙应用上传
vue.js·华为·uni-app