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

相关推荐
CHB17 小时前
uni-ai:让你的App快速接入AI
uni-app·deepseek
小徐_23333 天前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
iOS阿玮3 天前
永远不要站在用户的对立面,挑战大众的公知。
uni-app·app·apple
xw53 天前
uni-app中v-if使用”异常”
前端·uni-app
!win !3 天前
uni-app中v-if使用”异常”
前端·uni-app
2501_915918413 天前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张3 天前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
00后程序员张3 天前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
海绵宝宝不喜欢侬3 天前
uniapp-微信小程序分享功能-onShareAppMessage
微信小程序·小程序·uni-app
2501_915106323 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode