美文网首页
uniapp使用axios

uniapp使用axios

作者: Enginner_XZ | 来源:发表于2021-02-09 20:11 被阅读0次

    上代码

    import Vue from 'vue'
    import axios from 'axios'
    let baseURL = 'https://cp.kin168.top/'
    const instance = axios.create({
        baseURL,
        timeout : 6000
    })
    
    // 请求拦截
    instance.interceptors.request.use(
        config => {
            return config
        },
        error => {
            return Promise.reject( error );
        }
    );
    
    // 响应拦截
    instance.interceptors.response.use( res => {
        if ( res.status == 200 ){
            return res;
        } else {
            return Promise.reject( res.data.msg );
        }
    });
    
    // 自定义适配器 , 适配uniapp语法
    axios.defaults.adapter = function( config ) {
        return new Promise( ( resolve , reject ) => {
            let settle = require('axios/lib/core/settle');
            let buildURL = require('axios/lib/helpers/buildURL');
            uni.request({
                method : config.method.toUpperCase(),
                url : config.baseURL + 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 );
                },
            });
        })
    }
    
    export default instance
    

    相关文章

      网友评论

          本文标题:uniapp使用axios

          本文链接:https://www.haomeiwen.com/subject/gwmcxltx.html