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

相关推荐
00后程序员张9 小时前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
海绵宝宝不喜欢侬11 小时前
uniapp-微信小程序分享功能-onShareAppMessage
微信小程序·小程序·uni-app
2501_9151063211 小时前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode
xkxnq11 小时前
Uniapp崩溃监控体系构建:内存泄漏三维定位法(堆栈/资源/线程)
uni-app
Qlittleboy11 小时前
uniapp如何使用本身的字体图标
javascript·vue.js·uni-app
写代码的jiang11 小时前
打造精简高效的 uni-app 网络请求工具
uni-app
!win !18 小时前
uni-app项目支付宝端Input不受控
小程序·uni-app·支付宝小程序
xw519 小时前
uni-app项目支付宝端Input不受控
前端·uni-app·支付宝
百思可瑞教育1 天前
Vue.config.js中的Webpack配置、优化及多页面应用开发
前端·javascript·vue.js·webpack·uni-app·北京百思教育
百思可瑞教育1 天前
Vue中使用keep-alive实现页面前进刷新、后退缓存的完整方案
前端·javascript·vue.js·缓存·uni-app·北京百思可瑞教育