WebApp【公共组件库】@前端(For Git Submodule)
Tevin
2022-06-09 4ec143f5ff8ca81417fefc08362b4e1d6e3f713c
实现主机地址独立管理工具,第二部分
6 files modified
188 ■■■■ changed files
bases/Fetcher.js 154 ●●●● patch | view | raw | blame | history
bases/HostBoot.js 18 ●●●●● patch | view | raw | blame | history
bases/Pilot.js 5 ●●●●● patch | view | raw | blame | history
forms/chinaArea/ChinaLocations.weapp.js 4 ●●●● patch | view | raw | blame | history
forms/imagePicker/CImagePicker.vue 4 ●●●● patch | view | raw | blame | history
forms/userSignature/CUserSignature.vue 3 ●●●● patch | view | raw | blame | history
bases/Fetcher.js
@@ -6,6 +6,7 @@
import Taro from '@tarojs/taro';
import Qs from 'qs';
import { Tools } from '@components/common/Tools';
import { $hostBoot } from '@components/bases/HostBoot';
import project from '@project';
export class Fetcher {
@@ -17,16 +18,15 @@
    constructor(options = {}) {
        this._data = {
            urlPrefix: options.urlPrefix || ['/api/common/', '/api/common/'],
            mock: Tools.getUrlParam('mock') || project.host.mock,
        };
        if (this._data.mock === 'on') {
            if (project.host.assetsPath.indexOf('..') === 0) {
                this._defaultConfig.url = Fetcher.host + '/' + project.host.assetsPath.replace('/assets', '/mocks');
            } else {
                this._defaultConfig.url = Fetcher.host + project.host.assetsPath.replace('/assets', '/mocks');
            }
        } else {
            this._defaultConfig.url = Fetcher.host;
        // mock 模式转换地址
        if ($hostBoot.isOnMock()) {
            this._defaultConfig.url += (project.host.assetsPath.indexOf('..') === 0 ? '/' : '') +
                project.host.assetsPath.replace('/assets', '/mocks');
        }
        // 正常模式
        else {
            this._defaultConfig.url = '';
        }
    }
@@ -72,24 +72,13 @@
     */
    spellURL(devSuffix, serSuffix) {
        let url = '';
        // mock 模式
        if (this._data.mock === 'on') {
        // mock地址
        if ($hostBoot.isOnMock()) {
            url = this._data.urlPrefix[0].replace('api/', '') + devSuffix + '.json';
        }
        // 强制实际请求模式
        else if (this._data.mock === 'real') {
            url = this._data.urlPrefix[1] + (serSuffix || devSuffix);
        }
        // 正常模式
        // 正常地址
        else {
            // 开发环境地址
            if (Fetcher.inDevMod) {
                url = this._data.urlPrefix[0] + devSuffix;
            }
            // 生产环境地址
            else {
                url = this._data.urlPrefix[1] + (serSuffix || devSuffix);
            }
            url = this._data.urlPrefix[1] + (serSuffix || devSuffix);
        }
        const fixReg = /[a-zA-Z0-9]+\/\.\.\//;
        while (url.indexOf('../') >= 0) {
@@ -124,7 +113,8 @@
     * @return {Promise<any>}
     */
    post(url, data, options = {}) {
        if (this._data.mock === 'on') {
        // mock 模式转换为 get 请求
        if ($hostBoot.isOnMock()) {
            return this.get(url, data, options);
        }
        const params = Qs.stringify(data);
@@ -154,10 +144,17 @@
            if (process.env.TARO_ENV === 'weapp') {
                header['Cookie'] = this._getCookies();
            }
            // 如果指定了主机名,使用固定主机地址,否则使用默认地址
            let urlPrefix = '';
            if (options.hostName) {
                urlPrefix = $hostBoot.getHost(options.hostName) + this._defaultConfig.url;
            } else {
                urlPrefix = $hostBoot.getHost() + this._defaultConfig.url;
            }
            Taro.request({
                ...this._defaultConfig,
                header,
                url: this._defaultConfig.url + url,
                url: urlPrefix + url,
                method: type.toUpperCase(),
                data,
                success: response => {
@@ -347,7 +344,7 @@
            msg += '解析通讯数据异常!';
        }
        setTimeout(() => {
            this.message('fail', msg);
            this._message('fail', msg);
        }, 20);
    }
@@ -378,7 +375,7 @@
        } else if (response.state.code === 2001) {
            setTimeout(() => {
                if (typeof options.silence === 'undefined' || !options.silence) {
                    this.message('info', response.state.msg);
                    this._message('info', response.state.msg);
                }
            }, 20);
            return null;
@@ -396,7 +393,7 @@
        } else {
            setTimeout(() => {
                if (typeof options.silence === 'undefined' || !options.silence) {
                    this.message('error', response.state.msg);
                    this._message('error', response.state.msg);
                }
            }, 20);
            return null;
@@ -511,11 +508,11 @@
                }
                // 绝对路径
                if (/^(\/upload|\/static|\/mini|\/assets)/.test(path)) {
                    return Fetcher.host + path;
                    return $hostBoot.getHost() + path;
                }
                // 部分路径
                else {
                    return Fetcher.host + '/upload/' + path;
                    return $hostBoot.getHost() + '/upload/' + path;
                }
            }
            // 裁剪多余部分
@@ -562,104 +559,13 @@
     * @param type
     * @param msg
     */
    message(type, msg) {
    _message(type, msg) {
        Taro.showToast({
            title: msg,
            icon: 'none',
            mask: true,
            mask: false,
            duration: type === 'fail' ? 3000 : 2000,
        });
    }
    /**
     * 记录是否为本地开发模式
     * @type {Boolean}
     */
    static inDevMod = (() => {
        // 网页
        if (process.env.TARO_ENV === 'h5') {
            // http协议访问
            if (window.location.protocol.indexOf('http') > 0) {
                // 当内网 ip 且使用 33**/35** 的端口号时,视为本地开发模式
                return /^(192|127|localhost).*?:3[35]\d{2}$/i.test(window.location.host);
            }
            // 非http协议访问
            else {
                // 开发编译
                if (process.env.NODE_ENV === 'development') {
                    return true;
                }
                // 生产编译
                else if (process.env.NODE_ENV === 'production') {
                    return false;
                }
            }
        }
        // 小程序
        else if (process.env.TARO_ENV === 'weapp') {
            // 开发编译
            if (process.env.NODE_ENV === 'development') {
                return true;
            }
            // 生产编译
            else if (process.env.NODE_ENV === 'production') {
                return false;
            }
        }
    })();
    /**
     * 当前服务器主机地址
     * @type {String}
     */
    static host = (() => {
        // 网页模式
        if (process.env.TARO_ENV === 'h5') {
            // 如果网址参数有指定服务器
            const server = Tools.getUrlParam('server');
            if (server) {
                // 如果是完整网址,使用网址对应的域名
                if (server.indexOf('http') >= 0) {
                    const portal = server.split('//')[0];
                    const domain = server.split('//')[1].split('/')[0];
                    return portal + '//' + domain;
                }
                // 如果有匹配服务器,使用指定的服务器地址
                if (typeof project.host.hosts[server] !== 'undefined') {
                    return project.host.hosts[server];
                }
                // 否则使用本地
                else {
                    return project.host.hosts.lc;
                }
            }
            // 网页域名提取服务器地址
            else if (window.location.protocol.indexOf('http') >= 0) {
                return window.location.protocol + '//' + window.location.host;
            }
            // 既不指定server也不是域名访问,使用设置的服务器地址
            else {
                // 开发
                if (Fetcher.inDevMod) {
                    return project.host.hosts[project.host.devType];
                }
                // 生产
                else {
                    return project.host.hosts[project.host.serverType];
                }
            }
        }
        // 小程序模式
        else if (process.env.TARO_ENV === 'weapp') {
            // 开发
            if (Fetcher.inDevMod) {
                return project.host.hosts[project.host.devType];
            }
            // 生产
            else {
                return project.host.hosts[project.host.serverType];
            }
        }
    })();
}
bases/HostBoot.js
@@ -134,11 +134,10 @@
    /**
     * 获取当前主机地址
     * @param {string} hostName
     * @param {string} [hostName]
     * @return {string}
     */
    getHost(hostName) {
        hostName = hostName ? hostName : this._data.defaultHostName;
    getHost(hostName = this._data.defaultHostName) {
        if (typeof this._data.activeHost[hostName] === 'undefined') {
            return '';
        }
@@ -147,17 +146,24 @@
    /**
     * 获取当前主机类型简称
     * @param {string} hostName
     * @param {string} [hostName]
     * @return {string}
     */
    getTypeName(hostName) {
        hostName = hostName ? hostName : this._data.defaultHostName;
    getTypeName(hostName = this._data.defaultHostName) {
        if (typeof this._data.activeHost[hostName] === 'undefined') {
            return '';
        }
        return this._data.activeHost[hostName].typeName;
    }
    isOnMock(){
        if (this.isDevMod()) {
            return this.getTypeName() === 'lc';
        } else {
            return false;
        }
    }
}
export const $hostBoot = new HostBoot();
bases/Pilot.js
@@ -4,8 +4,7 @@
 */
import Taro, { getCurrentInstance, getCurrentPages } from '@tarojs/taro';
import { Fetcher } from './Fetcher';
import { Tools } from '@components/common/Tools';
import { $hostBoot } from '@components/bases/HostBoot';
import project from '@project';
export class Pilot {
@@ -145,7 +144,7 @@
            }
            // 小程序
            else if (process.env.TARO_ENV === 'weapp') {
                assets2[key] = Fetcher.host + project.host.assetsPath + asset;
                assets2[key] = $hostBoot.getHost() + project.host.assetsPath + asset;
            }
        });
        return assets2;
forms/chinaArea/ChinaLocations.weapp.js
@@ -4,15 +4,15 @@
 */
import Taro from '@tarojs/taro';
import { Fetcher } from '@components/bases/Fetcher';
import project from '@project';
import { $hostBoot } from '@components/bases/HostBoot';
const locationTree = [];
let ChinaLocationData = {};
let readyCallback = () => { };
Taro.request({
    url: Fetcher.host + project.host.assetsPath + '/datas/ChinaLocation.json',
    url: $hostBoot.getHost() + project.host.assetsPath + '/datas/ChinaLocation.json',
    header: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
forms/imagePicker/CImagePicker.vue
@@ -32,7 +32,7 @@
import Taro from '@tarojs/taro';
import { $ } from '@tarojs/extend';
import { AtInput, AtImagePicker, AtCurtain } from 'taro-ui-vue';
import { Fetcher } from '@components/bases/Fetcher';
import { $hostBoot } from '@components/bases/HostBoot';
import { $fetchCommon } from '@fetchers/FCommon';
import { Tools } from '@components/common/Tools';
import CImageCompressor from './CImageCompressor.vue';
@@ -175,7 +175,7 @@
            });
        },
        $uploadImage(callback) {
            const url = Fetcher.host + $fetchCommon.getUploadImgURL();
            const url = $hostBoot.getHost() + $fetchCommon.getUploadImgURL();
            const uploadTeam = [];
            const imgs = [];
            this.files.forEach(file => {
forms/userSignature/CUserSignature.vue
@@ -44,6 +44,7 @@
import { $bridge } from '@components/common/Bridge';
import project from '@project';
import './cUserSignature.scss';
import { $hostBoot } from '@components/bases/HostBoot';
export default {
    name: 'CUserSignature',
@@ -119,7 +120,7 @@
                header['Cookie'] = cookiesArr.join('; ');
            }
            Taro.uploadFile({
                url: Fetcher.host + $fetchCommon.getUploadImgURL(),
                url: $hostBoot.getHost() + $fetchCommon.getUploadImgURL(),
                header,
                filePath: file.url,
                fileName: file.fileName,