uniapp使用axios做网络请求时遇到adapter问题和axios0.19.0+版本不同无法请求

在uniapp开发中,使用axios进行网络请求时遇到adapterisnotafunction错误。通过引入特定代码解决了axios 0.19.0版本才能请求的问题。对于0.19.0之后的版本,需要额外处理buildFullPath,最终实现适配uniapp的axios网络请求,不受版本限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用uniapp开发时,由于习惯使用axios做网络请求框架,所以在uniapp开发时也想使用axios。但实际使用时并没有那么简单。

首先安装axios

npm install axios

请求时报 adapter is not a function 错误

网上有解决方案,在配置axios请求的地方引入一段代码就行

//真机获取 解决app上adapter is not a function问题
axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(config.url, 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);
			}
		})
	})
}

这样就可以请求了吗? 并不是那么绝对,只有axios 0.19.0可以请求成功,超过0.19.0还是无法请求。难道只能限制死0.19.0版本了吗?

不要担心,也有解决方案,原因是0.19.0版本之后的版本多了个buildFullPath 如果是之前的版本不需要buildFullPath,所以需要改一下adapter配置方案,代码如下

//真机获取 解决app上adapter is not a function问题
axios.defaults.adapter = function(config) {
	 return new Promise((resolve, reject) => {
			var settle = require('axios/lib/core/settle');
			var buildURL = require('axios/lib/helpers/buildURL');
			var buildFullPath = require('axios/lib/core/buildFullPath');
			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);
				}
			})
	    })
}

 ok,到这里完美解决在uniapp中使用axios无法请求的问题。并且不限制axios版本。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值