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

相关推荐
雪芽蓝域zzs21 小时前
uniapp 获取app版本信息(兼容鸿蒙)
uni-app
一颗小青松21 小时前
uniapp app端使用uniCloud云函数和云对象
uni-app
2501_916008891 天前
在 Windows 上使用开心上架(Appuploader)在 Windows 环境下创建与管理 iOS 证书
android·ios·小程序·https·uni-app·iphone·webview
qq_316837751 天前
uniapp打包的微信小程序和h5两个项目 微信小程序webview打开h5 ,h5发送消息到小程序
微信小程序·小程序·uni-app
fxshy1 天前
uniapp结合uniCloud开发的微信小程序,在开发本地接口可以正常,但是线上异常,配置服务器域名解决
微信小程序·小程序·uni-app
技术宅小温1 天前
< uni-app开发核心难点解析:框架适配与打包发布全流程踩坑指南 >
前端·前端框架·uni-app·web app
宠友信息2 天前
面向多端部署的社区平台技术方案:uniapp 与java微服务架构的工程化实践
java·微服务·微信·架构·uni-app·springboot
2501_915921432 天前
没有 iOS 源码的前提下如何进行应用混淆,源码混淆失效后的替代
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
Perfdog 成本变高之后,Windows 上还能怎么做 iOS APP 性能测试
android·ios·小程序·https·uni-app·iphone·webview
奶糖 肥晨2 天前
JS自动检测用户国家并显示电话前缀教程|vue uniapp react可用
javascript·vue.js·uni-app