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

相关推荐
Geek_Vison9 小时前
技术实践:保险健康APP引入第三方小程序实战,如何构建一个安全可控的沙箱环境~
android·安全·小程序·uni-app·mpaas
2501_9159184110 小时前
Python如何抓取HTTPS请求包的完整教程与代码示例
android·ios·小程序·https·uni-app·iphone·webview
2501_9160088911 小时前
全面解析常用Web前端开发工具:编辑器、调试工具、性能分析器与框架
android·前端·ios·小程序·uni-app·编辑器·iphone
编程猪猪侠12 小时前
基于uni-app-x 与 uni-app 的安卓与 H5 双向通信完整实现
android·javascript·uni-app
niech_cn1 天前
uniapp开发App(iOS、Android、鸿蒙Next)之新建项目相关细节(二)
uni-app
梦梦代码精1 天前
功能堆砌不如好扩展:4 款开源商城系统的选型思考
java·docker·uni-app·开源·php
巴巴博一1 天前
uni-app / 微信小程序中 open-type=“share“ 按钮样式异常,和普通 view 无法齐平的解决方案
微信小程序·uni-app·notepad++
游九尘2 天前
JavaScript 实现三段式版本号对比函数(app升级用)
javascript·uni-app
2501_916007472 天前
前端开发常用软件与工具全面指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915909062 天前
iOS应用性能优化:十大策略提升用户体验与开发效率
android·ios·小程序·https·uni-app·iphone·webview