Element-ui+axios+loading封装,支持多种ip域名,多种content-type类型

注: 使用的UI框架是element-ui, 由于封装过程需要使用自定义axios的config,因此使用的axios版本是 0.18.0

解析: 多种ip域名,多种content-type类型的原理, 利用axios的自定义config属性, 获取相应的内容

axios的请求响应

server.interceptors.request.use(config => {

	// token
    if (store.getters.token || tokenCookies.getToken()) {
        config.headers['X-Access-Token'] = tokenCookies.getToken();
    }
	// 获取baseUrl
    if(config['isBaseUrl']) {
        config.baseURL = ipConfig.utilsInterfaceIp();
    }
	// 获取ContentType
    if (!config['ContentType']) {
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
    }
    // 开启load加载
    if(config['showLoading']) {
        showFullScreenLoading()
    }
    config.headers['X-Requested-With'] = true;

    return config;
}, error => {
	// 关闭load加载
    tryHideFullScreenLoading()
    MessageError('客户端响应失败')
    return Promise.reject(error)
});

接口使用

// 使用默认ip,和content-type
export function getList(data) {
    return request({
        method: 'post',
        url: 'login',
        showLoading: true,
        data: data
    })
}

// 使用自定义的ip和content-type
export function login(data) {
    return request({
        method: 'post',
        url: 'login',
        currContentType: 'urlencoded',
        data,
        showLoading: false,
        requestUrl: 'http://127.0.0.1:3001/',
    })
}

1, 主要需要引入的包

npm install element-ui -S
npm install axios -S
npm install --save lodash

2, 首先ip域名的全局js

const ipConfig = process.env.NODE_ENV === 'production' ? {
		interfaceIp: () => 'http://118.31.68.77:9910/data-topic/', // ip域名1
		utilsInterfaceIp: () => 'http://118.31.68.51:9901/rbac/', // ip域名2
		homepageIp: () => 'http://118.31.68.77/rbac/' // 跳回主系统主页ip
	} : {
		interfaceIp: () => 'api', // 代理ip域名1 
		utilsInterfaceIp: () => 'utilsApi', // 代理ip域名2
		homepageIp: () => 'http://118.31.68.77/rbac/', // 跳回主系统主页ip
	}

3, 封装axios

import axios from 'axios/index'
import store from '../../store'
import {Message} from "element-ui";
import {MessageError} from "../custom/message";
import {ipConfig} from "../ip-map-config";
import {tokenCookies} from "../cookies";
import {showFullScreenLoading, tryHideFullScreenLoading} from "./loading";

const server = axios.create({
    baseURL: ipConfig.interfaceIp(),
    timeout: 50000 // 请求超时时间
});
const currContentType = {
    urlencoded: 'application/x-www-form-urlencoded;charset=utf-8',
    fromData: 'ipart/form-data;charset=utf-8',
    json: 'application/json;charset=utf-8',
    xml: 'text/xml;charset=utf-8'
}

server.interceptors.request.use(config => {

	// token
    if (store.getters.token || tokenCookies.getToken()) {
        config.headers['X-Access-Token'] = tokenCookies.getToken();
    }
	// 获取baseUrl
    if(config['isBaseUrl']) {
        config.baseURL = ipConfig.utilsInterfaceIp();
    }
	// 获取ContentType
    if (!config['ContentType']) {
         config.headers[ 'Content-Type'] = currContentType[config[currContentType]]
    }
    // 开启load加载
    if(config['showLoading']) {
        showFullScreenLoading()
    }
    config.headers['X-Requested-With'] = true;

    return config;
}, error => {
	// 关闭load加载
    tryHideFullScreenLoading()
    MessageError('客户端响应失败')
    return Promise.reject(error)
});

server.interceptors.response.use(response => {
    tryHideFullScreenLoading()
    if (response.status === 200) {
        let isSuccess = false;
        if(typeof(response.data.success) != undefined && response.data.success){
            isSuccess = true;
        } else if(typeof(response.data.code) != undefined && response.data.code == 0){
            isSuccess = true;
        }
        if(!isSuccess){
            // error handle
            codeSuccess(response)
            return;
        }
        // success handle
        return response;

    }else {
        return Promise.reject(response)
    }
}, error => {
    tryHideFullScreenLoading
    MessageError('服务器响应失败')
    return Promise.reject(error)
});

function codeSuccess(response) {
    const code = response.data.code || null
    if(code == -9) {
        Message.error({
            message: '登录失效',
            showClose: true,
            duration: 2000,
            onClose() {
                location.href = ipConfig.homepageIp() + '#/login'
            }
        })

    }else {
        MessageError('网络连接出错')
    }
}


export default server;

4, emenelt-ui的load的全局封装

// 全局loading
import {Loading} from 'element-ui'
import _ from 'lodash'

//loading对象
let loading

// 当前正在请求的数量
let needLoadingRequestCount = 0
// 声明一个对象用于储存请求个数
export const showFullScreenLoading = function (target, message) {
    if (needLoadingRequestCount === 0) {
        startLoading(target, message)
    }
    needLoadingRequestCount++
}

function startLoading(target, message) {
    // 后面这个判断很重要,因为关闭时加了抖动,此时loading对象可能还存在,
    // 但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
    if (needLoadingRequestCount === 0 && !loading) {
        loading = Loading.service({
            lock: true,
            text: message || '拼命加载中……',
            background: 'rgba(255, 255, 255, 0.5)',
            target: target || "body"
        })
    }
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); //做个保护,给定的一组数字中的最大值
    if (needLoadingRequestCount === 0 && loading) {
        //防抖:将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时, loading闪烁的问题。
        tryCloseLoading()
    }
}

const tryCloseLoading = _.debounce(() => {
    loading.close()
    loading = null;
}, 300)

发布了17 篇原创文章 · 获赞 43 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/mf_717714/article/details/103143731