WebApp【公共组件库】@前端(For Git Submodule)
Tevin
2020-12-21 bde60a4ab1c176bef2f15a36b5e355708a4a1939
bases/Fetcher.js
@@ -3,9 +3,7 @@
 * @author Tevin
 */
import Axios from 'axios';
import Qs from 'qs';
import {message, Modal} from 'antd';
import Taro from '@tarojs/taro';
import {Tools} from '@components/common/Tools';
export class Fetcher {
@@ -16,23 +14,22 @@
     */
    constructor(options = {}) {
        this._data = {
            urlPrefix: options.urlPrefix || ['/api/common', '/api/common'],
            urlPrefix: options.urlPrefix || ['/api/common/', '/api/common/'],
        };
    }
    /**
     * 请求配置
     * @type {{headers: Object, baseURL: string, responseType: string, timeout: number}}
     * @private
     */
    _defaultConfig = {
        baseURL: window.location.protocol + '//' + window.location.host,
        headers: {
        url: window.location.protocol + '//' + window.location.host,
        header: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Ax-Rq-Type': 'separation',
        },
        responseType: 'json',
        dataType: 'json',
        timeout: 10000,
    };
@@ -61,18 +58,17 @@
    }
    /**
     * 将 post 参数转换为 get 参数,并拼接 url
     * @param url
     * @param data
     * 显示提示信息
     * @param type
     * @param msg
     */
    parseParamUrl(url, data) {
        const params = Qs.stringify(data);
        if (url.indexOf('?') >= 0) {
            url += '&' + params;
        } else {
            url += '?' + params;
        }
        return url;
    message(type, msg) {
        Taro.showToast({
            title: msg,
            icon: 'none',
            mask: true,
            duration: type === 'error' ? 5000 : 3000,
        });
    }
    /**
@@ -84,8 +80,7 @@
     * @return {Promise<any>}
     */
    get(url, data, remap = [], options = null) {
        const url2 = this.parseParamUrl(url, data);
        return this.query('get', url2, null, remap, options);
        return this.query('get', url, null, remap, options);
    }
    /**
@@ -97,13 +92,7 @@
     * @return {Promise<any>}
     */
    post(url, data, remap = [], options = null) {
        // mock 模式
        if (Fetcher.inMockMod) {
            return this.get(url, data, remap, options);
        }
        // 正常模式
        const params = Qs.stringify(data);
        return this.query('post', url, params, remap, options);
        return this.query('post', url, data, remap, options);
    }
    /**
@@ -116,35 +105,32 @@
     * @return {Promise<any>|}
     */
    query(type, url, data = null, remap, options) {
        if (!type || !/^get|post|put$/i.test(type) || !url) {
            return Promise.reject();
        }
        const method = type.toLowerCase();
        const response = Axios[method](url, data, {
            ...this._defaultConfig,
            ...options,
        });
        return response
            .then(response => {
                /**
                 * @type {{state: {code, http, msg}, data: Object}}
                 * @example response.state.code
                 *  2000  通用请求成功
                 *  2001  请求成功,但是没有数据,弹窗提示 msg(仅特殊情况使用)
                 *  5000  通用请求失败,弹窗提示 msg
                 *  9001  登陆已过期,弹窗提示过期且返回登陆页
                 *  9002  已登陆但没有操作权限,弹窗提示 msg
                 */
                const responseData = this._adaptiveResponseData(response.data);
                responseData.state.http = response.status;
                return this._transformResponseData(responseData, remap);
            })
            // HTTP 异常
            .catch((err) => {
                this._resolveCaughtNetErr(err);
                console.log('query error', err);
                return null;
        return new Promise((resolve, reject) => {
            Taro.request({
                ...this._defaultConfig,
                url: this._defaultConfig.url + url,
                method: type.toUpperCase(),
                data,
                success: response => {
                    /**
                     * @type {{state: {code, http, msg}, data: Object}}
                     * @example response.state.code
                     *  2000  通用请求成功
                     *  2001  请求成功,但是没有数据,弹窗提示 msg(仅特殊情况使用)
                     *  5000  通用请求失败,弹窗提示 msg
                     *  9001  登陆已过期,弹窗提示过期且返回登陆页
                     *  9002  已登陆但没有操作权限,弹窗提示 msg
                     */
                    const responseData = this._adaptiveResponseData(response.data);
                    responseData.state.http = response.statusCode;
                    resolve(this._transformResponseData(responseData, remap));
                },
                fail: error => {
                    this._resolveCaughtNetErr(error);
                    reject(null);
                },
            });
        });
    }
    /**
@@ -207,8 +193,8 @@
     */
    _resolveCaughtNetErr(err) {
        let msg = '';
        if (err.response && err.response.status) {
            switch (err.response.status) {
        if (err && err.status) {
            switch (err.status) {
                case 400:
                    msg += '通讯请求有误!(400 Bad Request)';
                    break;
@@ -243,7 +229,7 @@
        } else {
            msg += '解析通讯数据异常!';
        }
        message.error(msg);
        this.message('error', msg);
    }
    /**
@@ -276,12 +262,12 @@
                return response.data;
            }
        } else if (response.state.code === 2001) {
            message.info(response.state.msg);
            this.message('info', response.state.msg);
            return null;
        } else if (response.state.code === 9001) {
            this._showLoginExpired();
            // this._showLoginExpired();
        } else {
            message.error(response.state.msg);
            this.message('error', response.state.msg);
            return null;
        }
    }
@@ -496,8 +482,8 @@
        if (Tools.getTopUrlParam('query') === 'real') {
            return false;
        }
        // 当没有 url 指定时,只有内网 ip 和 35** 的端口号,视为本地开发模式
        return /^(192|127|localhost).*?:35\d{2}$/i.test(window.location.host);
        // 当没有 url 指定时,只有内网 ip 和 33** 的端口号,视为本地开发模式
        return /^(192|127|localhost).*?:33\d{2}$/i.test(window.location.host);
    })();