vue项目中axios的封装(简单版)

代码结构:

 

 axios-json.js 的代码:

import axios from 'axios'
import storage from '@/util/storage'
// import Qs from 'qs'
import router from '@/router/index'
import store from '@/store/index'
import Element from 'element-ui'
import {openPageLoading,closePageLoading} from "@/util"
function getRootPath_dc() {
    let pathName = window.location.pathname.substring(1);
    let webName = pathName =='' ?'' : pathName.substring(0, pathName.indexOf('/'));
    if (webName =="") {
        return window.location.protocol +'//' + window.location.host;
    }
    else {
        return window.location.protocol +'//' + window.location.host +'/' + webName;
    }
}
let apiJsonpParam = null;
if(process.env.NODE_ENV=='development'){
    apiJsonpParam = {
        headers: {'Content-Type': 'application/json;charset=utf-8'},
        timeout: 5000,
        responseType: 'json'
    }
} else {
    apiJsonpParam = {
        headers: {'Content-Type': 'application/json;charset=utf-8'},
        timeout: 5000,
        responseType: 'json',
        baseURL:getRootPath_dc()
    }
}
const apiJson = axios.create(apiJsonpParam)

let serviceLoadingNum = 0
let serviceLoadingTem = null

apiJson.interceptors.request.use(
    request => {
        // 打开遮罩层
        if(request.loading==undefined || request.loading==true){
            clearTimeout(serviceLoadingTem)
            openPageLoading()
            serviceLoadingNum ++
        }
        if(store.state.user.token){
            request.headers['access_token']=store.state.user.token;
            storage.local.remove('tokenid')
        }
        if(storage.local.get('tokenid')){
            request.headers['tokenid']=storage.local.get('tokenid');
        }
        if(request.method=='get'){
            let url = request.url;
            if(request.url.indexOf('?')>-1){
                request.url= url+'&randomnumber='+Math.random();
            } else {
                request.url= url+'?randomnumber='+Math.random();
            }
            
        }
        return request
    },
    error=>{
        return Promise.reject(error)
    }
)

apiJson.interceptors.response.use(
    response => {
        // 关闭遮罩层
        if(response.config.loading==undefined || response.config.loading==true){
            serviceLoadingNum --
            if(serviceLoadingNum==0){
                serviceLoadingTem = setTimeout(()=>{
                    closePageLoading()
                },10)
            }
        }
        // 系统内接口业务报错统一处理
        if (!response.data.success) {
            // console.log(response.data,"response.data");
            let message = response.data.message || response.data.msg || response.msg;
            if(response.data.code){
                handleError(response.data.code, message);
                return Promise.reject(response.data)
            }          
        } else {
            return Promise.resolve(response.data.result);
           
        }
    },
    error => {
        if(error && error.response){
            if(error.response.config.loading==undefined || error.response.config.loading==true){
                serviceLoadingNum --
                if(serviceLoadingNum==0){
                    serviceLoadingTem = setTimeout(()=>{
                        closePageLoading()
                    },10)
                }
            }
            handleError(error.response.status)
            return Promise.reject(error.response)
        }
        return Promise.reject(error)
    }
)
export function handleError(errorCode,errormsg=''){
    switch (errorCode) {
        // 401: 未登录
        case 401:
            Element.Message.error("登录失效,请重新登录!")
            break;
        // 404请求不存在
        case 404:
            Element.Message.error("请求接口不存在!");
            break;
        case 400:
            Element.Message.error('400')
            break;
        case 500:
                let errMsg=errormsg||"服务正在维护中,请稍后...";
                // Element.Message(errMsg);
                Element.Message({
                    showClose: true,
                    message: errMsg,
                    type: 'error'
                  });
                break;
        // 其他错误,直接抛出错误提示
        default:
                Element.Message({
                    showClose: true,
                    message:'服务发生异常,请稍后重试!',
                    type: 'error'
                })
    }
}
export default apiJson

针对 axios-json.js 中的 import {openPageLoading,closePageLoading} from "@/util" ,其中 util 文件夹下 index.js 里面的这两个方法为:

import Element from 'element-ui'
// 打开遮罩层
export function openPageLoading(){
    Element.Loading.service({
        fullscreen: true,
        lock: true,
        text: '正在加载中,请稍候 ...',
        spinner: 'el-icon-loading',
        // spinner: 'ri-loader-2-line',
        background: 'rgba(255, 255, 255, 0.4)'
    })
}
// 关闭遮罩层
export function closePageLoading(){
    Element.Loading.service().close();
}

main.js 中的相关代码:

import apiJson, {handleError} from './api/axios-json'
Vue.prototype.$apiJson = apiJson
Vue.prototype.$handleError=handleError;    //此方法可能没用,做个参考

用法:

async getFuncExample(){
    let url = "xxx";
    let params={id:"xxx"}
    let res;
    await res = apiJson.get(url, { params });
}

async postFuncExample(){
    let url = "xxx";
    let params={id:"xxx"}
    let res;
    await res = apiJson.get(url, params);
}

 

posted @ 2022-06-20 16:11  smil、梵音  阅读(1167)  评论(0编辑  收藏  举报