1***@qq.com
1***@qq.com
  • 发布:2019-12-23 10:40
  • 更新:2023-08-16 11:48
  • 阅读:16679

uni-app 使用axios 分享 ,解决: adapter is not a function

分类:uni-app

uni-app 使用axios 真机会提示: adapter is not a function 。我也不懂,我也不会,就菜鸟一个。

然后跟了下问题所在,好像调用不到xhr.js ,
翻到这里 var adapter = config.adapter || defaults.adapter; 报错。

参考:
https://juejin.im/post/5dbd8c64e51d4529fc3facd4
https://blog.csdn.net/u013704958/article/details/90713386 我借鉴5楼提供的方法,用uni.request 来调用
https://ext.dcloud.net.cn/plugin?id=930

添加了一段代码,重新引用
//真机获取
axios.defaults.adapter = function (config) {....}

下面axios封装来自大佬的 HzyAdmin 项目
https://gitee.com/hzy6/HzyAdminSpa

import axios from 'axios';  
import qs from 'qs';  
import tools from './tools';  

let loading;  
let isloading = true;  
//http request 拦截器  
axios.interceptors.request.use(config => {  
        if (isloading) {  
            uni.showLoading();  
            loading=true;  
        }  
        var cookie = uni.getStorageSync('Authorization');  
        config.headers['x-requested-width'] = 'XMLHttpRequest';  
        config.headers['Authorization'] = cookie;  
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';  

        if (!config.data) return config;  

        if (config.data.isUpload)  
            config.headers['Content-Type'] = 'multipart/form-data';  
        else  
            config.data = qs.stringify(config.data); //如果是非上传类型 则 将数据重新组装  

        return config;  
    },  
    error => {  
        console.log(error);  
        return Promise.reject(error);  
    });  

//http response 拦截器  
axios.interceptors.response.use(response => {  
        if (loading) {  
            uni.hideLoading();  
            loading=false;  
        }  
        var data = response.data;  

        if (data.hasOwnProperty('status')) {  
            // public enum EMessageBoxStatus  
            // {  
            //     接口授权码无效 = -3,  
            //     服务端异常 = -2,  
            //     自定义 = -1,  
            //     失败 = 0,  
            //     成功 = 1,  
            // }  

            if (data.status == -3) { //接口授权码无效global.$router.push("/Login")  
                tools.alert(data.msg + '请重新登录!', () => uni.navigateTo({url:'../pages/Login'}));  
                return;  
            }  
            if (data.status == -2) { //服务端异常  
                tools.alert(data.msg);  
                return;  
            }  
            if (data.status == 0) { //失败  
                tools.msg(data.msg, '错误');  
                return;  
            }  
        }  

        return response;  
    },  
    error => {  
        console.log(error);  
        uni.hideLoading();  
        if (error.response.status === 401) {  
            if (loading) {  
                loading=false;  
            }  
            global.tools.notice("无权访问!", "错误");  
            return uni.navigateTo({url:'../pages/Login'}) //global.$router.push('/Login');  
        } else {  
            return Promise.reject(error)  
        }  
    });  

//真机获取  
axios.defaults.adapter = function (config) {  
    return new Promise((resolve, reject) => {  
        console.log(config)  
        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);  
            }  
        })  
    })  
}  

/**  
 * 封装get方法  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param headers 头部信息  
 * @returns {Promise}  
 */  
export function get(url, data = {}, loading = true, config = {}) {  
    isloading = loading;  
    url =`${url}?${qs.stringify(data)}`;  
    return new Promise((resolve, reject) => {  
        axios.get(url, config)  
            .then(response => {  
                resolve(response);  
            })  
            .catch(err => {  
                reject(err)  
            })  
    })  
}  

/**  
 * 封装post请求  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */  
export function post(url, data = {}, loading = true, config = {}) {  
    isloading = loading;  
    return new Promise((resolve, reject) => {  
        axios.post(url, data, config)  
            .then(response => {  
                if (response != undefined) {  
                    resolve(response);  
                }  
            }, err => {  
                reject(err)  
            })  
    })  
}  

/**  
 * 封装 post 请求 用于上传文件   
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */  
export function upload(url, data = {}, loading = true, config = {}) {  
    isloading = loading;  
    if (!data) data = {};  
    data.isUpload = true;  
    return new Promise((resolve, reject) => {  
        axios.post(url, data, config)  
            .then(response => {  
                if (response != undefined) {  
                    resolve(response);  
                }  
            }, err => {  
                reject(err)  
            })  
    })  
}  

/**  
 * 封装 get请求 用于下载文件  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @returns {Promise}  
 */  
export function download(url, data = {}, loading = true) {  
    this.get(url, data, loading, {  
        // responseType: 'stream',  
        responseType: 'blob',  
        // responseType: 'arraybuffer',  
    }).then(res => {  
        var data = res.data;  
        var headers = res.headers;  
        //"attachment; filename=6a9c13bc-e214-44e4-8456-dbca9fcd2367.xls;filename*=UTF-8''6a9c13bc-e214-44e4-8456-dbca9fcd2367.xls"  
        var contentDisposition = headers['content-disposition'];  
        var contentType = headers['content-type'];  
        var attachmentInfoArrary = contentDisposition.split(';');  
        var fileName = '';  
        if (attachmentInfoArrary.length > 1) {  
            fileName = attachmentInfoArrary[1].split('=')[1];  
        }  
        var blob = new Blob([data], { type: contentType });  

        if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE  
            window.navigator.msSaveOrOpenBlob(blob, fileName);  
        } else {  
            let url = (window.URL || window.webkitURL).createObjectURL(blob);  
            // window.open(url, "_blank"); //下载  
            // window.URL.revokeObjectURL(url) // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。  

            let a = document.createElement('a');  
            a.style.display = 'none';  
            a.href = url;  
            a.setAttribute('download', fileName);  
            document.body.appendChild(a);  
            a.click()  
            document.body.removeChild(a); // 下载完成移除元素  
            // window.location.href = url  
            window.URL.revokeObjectURL(url); // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。  

        }  
    });  
}  

/**  
 * 封装patch请求  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */  
export function patch(url, data = {}, loading = true, config = {}) {  
    isloading = loading;  
    return new Promise((resolve, reject) => {  
        axios.patch(url, data, config)  
            .then(response => {  
                resolve(response);  
            }, err => {  
                reject(err)  
            })  
    })  
}  

/**  
 * 封装put请求  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */  
export function put(url, data = {}, loading = true, config = {}) {  
    isloading = loading;  
    return new Promise((resolve, reject) => {  
        axios.put(url, data, config)  
            .then(response => {  
                resolve(response);  
            }, err => {  
                reject(err)  
            })  
    })  
}
4 关注 分享
2***@qq.com 猫猫儿 7***@qq.com 3***@qq.com

要回复文章请先登录注册

1***@qq.com

1***@qq.com

我问下,使用这个适配器后,axios 就没法使用 「onDownloadProgress」这个方法了,我问下是没法使用这个方法了吗?

楼主知道,怎么解决么,大概就是在 app 和 h5 和 小程序平台都支持 onDownloadProgress这个方法

环境:h5 和 app
axios 版本:0.27.2
2023-08-16 11:48
AscenX

AscenX

uni.request不支持patch,你axios适配器用的就是uni.request,封装的patch还是没用啊
2021-11-24 14:17
K***@163.com

K***@163.com

回复 1***@qq.com :
怎么在页面上引用?发送请求?
2021-11-03 10:36
阿里云111

阿里云111

【阿里云】双11爆款优惠特价服务器
1核2G1M 180元/3年
2核2G5M 58元/1年
2核4G5M 600元/3年
4核8G5M 1500/3年
活动地址:
[https://www.aliyun.com/minisite/goods?taskPkg=1111ydsrwb&pkgSid=5985&userCode=wbqjs7bw](https://www.aliyun.com/minisite/goods?taskPkg=1111ydsrwb&pkgSid=5985&userCode=wbqjs7bw)

【腾讯云】双11爆款优惠特价服务器
1核2G5M 50G云盘,50元/1年
2核4G8M 80G云盘,74元/1年
2核4G3M 50G云盘,968元/3年(16:00开抢)
4核8G5M 50G云盘,818元/1年(19:00开抢)
活动地址:
[https://curl.qcloud.com/mMBBtBDp](https://curl.qcloud.com/mMBBtBDp)
2021-11-03 10:21
K***@163.com

K***@163.com

怎么使用啊
2021-11-03 10:19
m***@126.com

m***@126.com

回复 1***@qq.com :
好像每个页面都需要单独引入,没办法跟vue一样全局挂载axios
2021-01-16 12:32
1***@qq.com

1***@qq.com (作者)

回复 m***@126.com :
没用么? 重新引用自带的路径
var settle = require('axios/lib/core/settle');
var buildURL = require('axios/lib/helpers/buildURL');
2021-01-08 10:35
m***@126.com

m***@126.com

并没有用,还是报错
2020-12-29 16:37
落叶雨飘零

落叶雨飘零

patch可以用不
2020-11-03 12:55
8***@qq.com

8***@qq.com

回复 cathayIT :
//app真机获取
http.defaults.adapter = function (config) {
return new Promise((resolve, reject) => {
const settle = require('axios/lib/core/settle');
const buildURL = require('axios/lib/helpers/buildURL');
uni.request({
method: config.method.toUpperCase(),
url: buildURL(URL + config.url, config.params),
header: config.headers,
data: config.data,
responseType: config.responseType,
complete: function complete(response) {
response = {
data: response.data,
status: response.statusCode,
errMsg: response.errMsg,
header: response.header,
config: config
};
settle(resolve, reject, response)
}
})
})
}
2020-07-15 10:40