request.js 2.61 KB
/*
 * @Description: 
 * @Autor: renchao
 * @LastEditTime: 2023-05-16 09:17:28
 */
/**
 * 此文件主要创建 axios 实例,然后添加请求拦截器和响应拦截器
 */
import axios from 'axios'
import { Message } from 'element-ui'
import { endLoadingSubCount } from './requestLoading'

// create an axios instance
const service = axios.create({
    baseURL:
        process.env.NODE_ENV == "development"
            ? process.env.VUE_APP_BASE_API
            : window.baseUrl + "/",
    withCredentials: true,  //是否允许跨域
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    timeout: 15000
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        if (process.env.NODE_ENV === "production") {
            return config;
        } else {
            config.headers.Authorization = authorization;
            return config;
        }
    },
    error => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        /**
         *  对响应数据判断:
         *  如果成功返回数据,就通过return把数据返出去
         *  如果请求不成功,就在拦截器这里统一处理(组件的代码就不用关注错误的情况了)
         */
        if (response.status == 200) {
            return response.data;
        } else {
            handleErrorData(response.data);
        }
        return response;
    },
    error => {
        endLoadingSubCount()
        // 对响应错误做点什么
        Message({
            message: '服务器异常,请联系管理员',
            type: 'error',
            duration: 5 * 1000,
            customClass: 'messageIndex'
        })
        return Promise.reject(error);
    }
)
//对错误信息的处理函数
function handleErrorData (errMes) {
    if (errMes.message) {
        Message.error(errMes.message);
    } else {
        switch (errMes.code) {
            case 401:
                Message.error("未授权,请重新登录!");
                break;
            case 403:
                Message.error("拒绝访问");
                break;
            case 404:
                Message.error("很抱歉,资源未找到!");
                break;
            case 500:
                Message.error("服务器错误!");
                break;
            default:
                Message.error("服务正在联调中,请稍后!");
                break;
        }
    }
}
export default service