Vue项目中axios的二次封装和使用

1、axios的全局配置和封装

src/axios/index.js

1.1 依赖

import axios from 'axios';
import { getToken } from 'utils/auth';
import { MessageBox, Notification, Loading } from 'element-ui';

// 定义一个loading组件实例对象,方便接口调用设置全局页面loading
var loadingInstance;

// 常用错误提示
const errorCode = {
    '401': '认证失败,无法访问系统资源',
    '403': '当前操作没有权限',
    '404': '访问资源不存在',
    'default': '系统未知错误,请反馈给管理员'
};

1.2 基础配置

// 基础配置
const Axios = axios.create({
    baseURL: '',
    timeout: 20000,
    responseType: 'json',
    headers: {
        'Content-Type': 'application/json;chartset=utf-8',
    },
    isToken: true, // 默认true表示接口调用需要请求头加token,false表示不需要token即可调用
    showLoading: true, // 显示loading的配置,默认true显示,false不显示
    showError: true, // 是否弹框显示接口请求的错误信息,默认true显示,false不显示
});

1.3 请求拦截器

// 请求拦截器---------------------------------------------------------------------------
Axios.interceptors.request.use(config => {
    console.log('请求拦截', config);

    // 调接口是否需要设置token
    if (getToken() && config.isToken) {
        config.headers['Authorization'] = 'Bearer ' + getToken(); // 请求头上加token
    }
    // 避免ie浏览器get请求直接取缓存
    // if (config.method === 'get') {
    //     config.params.t = new Date().getTime();
    // }
    // 接口请求过程中显示全屏的loading
    if (config.showLoading) {
        // 防止一次请求结束后关闭loading,导致多次请求会刷新多次出现闪屏的问题
        if (window.loadingCloseTimeOut) {
            clearTimeout(window.loadingCloseTimeOut);
        }
        // 设置loading
        loadingInstance = Loading.service({
            fullscreen: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0.4)'
        });
    }
    return config;
}, error => {
    loadingInstance.close(); // 请求失败关闭loading
    console.log(error);
    return Promise.reject(error);
});

1.4 响应拦截器

// 响应拦截器----------------------------------------------------------------------------
Axios.interceptors.response.use(res => { // status状态码300及以下走这里处理
    console.log('响应拦截', res);
    
    // 防止一次请求结束后关闭loading,导致多次请求会刷新多次出现闪屏的问题
    if (loadingInstance) {
        window.loadingCloseTimeOut = setTimeout(() => {
            loadingInstance.close();
        }, 200)
    }

    // 二进制数据直接返回
    if (res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer'){
        return res.data
    }

    // res.status状态码,res.data.code表示res.status为200时,接口返回的值里面的状态码code
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = res.data.msg || errorCode[code] || errorCode['default'];
    if (code === 200) {
        return res.data;
    } else if (code === 401) {
        MessageBox.confirm('登录超时,请重新登录!', '登录超时', {
            type: 'warning',
            showClose: false,
            showCancelButton: false,
        }).then(() => {
            // 退出跳转登录页
            this.$router.push({name: 'Login'});
        }).catch(() => {});
        return Promise.reject(res.data);
    } else {
        if (res.config.showError) {
            Notification.error({
                title: '错误',
                message: msg,
            });
        }
        return Promise.reject(res.data);
    }
}, error => { // status状态码300以上走这里处理
    if (loadingInstance) {
        loadingInstance.close(); // 响应失败关闭loading
    }
    if (error.config.showError) {
        Notification.error({
            title: '错误',
            message: '服务器异常,请联系管理员!',
        });
    }
    console.log('error', error);
    return Promise.reject(error);
});

1.5 export default Axios

export default Axios;

2、axios的二次封装

src/axios/api.js

// Axios 基础配置的参数都可以在二次封装使用时对具体接口单独设置
import Axios from 'src/axios/index.js'

// 默认使用
export function GetConfig(params) {
    return Axios({
        url: 'sys/config/getConfig',
        method: 'get',
        params,
    });
}

// 设置isToken、showLoading
export function Login(data) {
    return Axios({
        url: '/login',
        method: 'post',
        data: data,
        isToken: false, // 接口不需要token
        showLoading: false, // 接口请求过程中不需要全局loading
    });
}

// 设置showError
export function GetInfo() {
    return Axios({
        url: '/getInfo',
        method: 'get',
        showError: false,
    });
}

// 设置responseType、headers
export function FileDownload(params) {
    return Axios({
        url: 'sys/file/download',
        method: 'get',
        params,
        responseType: 'blob',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
            'x-Requested-With': 'XMLHttpRequest'
        }
    });
}

// 设置timeout
export function Logout() {
    return Axios({
        url: '/logout',
        method: 'post',
        timeout: 50000,
    });
}

3、Vue组件中调用封装好的接口请求

<template>
    <div>接口调用</div>
</template>
<script>
import { GetConfig, GetInfo } from 'src/axios/api.js';
export default {
    name: 'example',
    data() {
        return {};
    },
    methods: {
        getConfig() {
            GetConfig({}).then(res => {
                console.log(res);
            })
        },
        getInfo() {
            GetInfo().then(res => {
                console.log(res);
            }).catch(error => {
                // 设置showError: false,可在此处单独设置错误提示
                console.log(error);
            })
        },
    }
}
</script>
<style scoped>
</style>

猜你喜欢

转载自blog.csdn.net/sleepwalker_1992/article/details/127111025