【js】https封装请求

httpConfig.js + https.js + 公共方法

1.httpConfig.js

//  参数配置表
let ipDeault = 'https://xxxx.e24health.com'; 
// let urlAddress = '/xxxx/';  
let urlAddress = '/xxxxEncrypt/'; //加密接口    
let errorCodeArr = ["010400xx", "010400xx", "010400xx", "0104xxx5", "01040xxx7", "01040xxx", "01040xxx"] //固定错误提示数组


const httpConfig = {
    //默认的URLIp路径
    ipDeault: ipDeault,

    //默认的URL地址路径
    urlAddress: urlAddress,

    // AuthorizationToken值
    authorizationToken: 'Basic xxxxx==',

    //固定错误提示数组
    errorCodeArr: errorCodeArr,

    //Copyright
    Copyright: 'Copyright © 2018 - 2021 深圳市xxx医疗技术开发有限公司',

    //DownUrl 服务下载地址 
    DownUrl: 'xxx/setup.exe',

}

export { httpConfig }

2.https.js

// 请求封装
// urlDeault   默认地址
// urlADS    增删改地址
// urlS      查询地址
import {
    message
} from 'antd';
import { httpConfig } from './httpConfig'
import { Keup, Util, Aes } from '../../tools/index'
// import store from '../store/'

// authorizationToken token
// ipDeault  默认的URLIp地址
// urlAddress 接口地址路径
// errorCodeArr 固定错误提示数组
const { authorizationToken, ipDeault, urlAddress, errorCodeArr } = httpConfig

export const $http = {
    ipDeault: ipDeault,
    UrlEncode: (obj) => {
        if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') {
            return '';
        }
        let params = [];
        for (let key in obj) {
            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
        }
        return params.join('&');
    },
    post: (type, Nothis, Objson) => {
        let formData = Object.assign({}, Objson.data);
        let url = $http.ipDeault;
        let httpUrlAddress; //完整地址
        let { userData } = window.sessionStorage
        let { ipConfig } = window.sessionStorage
        formData.code = Objson.code;
        if (userData) {
            let user = JSON.parse(userData)
            let ip = JSON.parse(ipConfig)
            formData.session = [{
                "userID": user.userID || '',
                "locID": user.locID || '',
                "groupID": user.groupID || '',
                "hospID": user.hospID || '',
                "sessionID": user.sessionID || '',
                'hospCode': user.hospCode || '',
                "language": user.language || '',
                "hostName": ip.hostName || '',
                "ipv4": ip.ipv4 || '',
                "ipv6": ip.ipv6 || '',
                "mac": ip.mac || '',
            }]
        }

        if (type !== 'urlDeault') {
            //type === 'urlADS' ? url = window.sessionStorage.productIP : url = window.sessionStorage.queryIP
        }
        //  未配置ip地址 采用默认的ip地址
        if (!url || url === '') {
            url = $http.ipDeault;
        }
        httpUrlAddress = url + urlAddress
		if(httpUrlAddress.indexOf("https://")>=0){
			httpUrlAddress
		}else{
			if(httpUrlAddress.indexOf("http://")<0){
				httpUrlAddress='http://' + httpUrlAddress
			}
		}
        fetch(httpUrlAddress, {
            method: 'post',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                "Authorization": authorizationToken,
                "Access-Control-Allow-Origin": ipDeault
            },
            body: httpUrlAddress.includes('Encrypt') ? Aes.Encrypt(JSON.stringify(formData)) : JSON.stringify(formData)
        }).then((res) => {
            if (res.status !== 200) {
                throw res.status
            } else {
                let Data;
                // 是否是加密请求
                httpUrlAddress.includes('Encrypt') ? Data = res.text() : Data = res.json()
                return Data
            }
        }).then((Data) => {
            let res
            httpUrlAddress.includes('Encrypt') ? res = JSON.parse(Aes.Decrypt(Data)) : res = Data
            res.errorCode = res.errorCode.toString(); //转成String类型

            if (res.errorCode !== '0') {
                if (errorCodeArr.includes(res.errorCode)) {
                    Keup.ModalMessage(3, Nothis, res.errorMessage, '跳转到登录页', '/login', "现在就去", 'error')
                } else {
                    if (Util.isEmpty(res.errorFlag)) { //挂号建卡,单独处理error弹框
                        message.error(res.errorMessage);
                    }
                }
            }
            Objson.success.call(Nothis, res)
        }).catch((error) => {
            if (Objson.error) {
                Objson.error.call(Nothis, error)
            }
        });
    },
    get: (type, Nothis, Objson) => {
        let Alldata = ''; // get后缀
        let url = $http.ipDeault;
        let httpUrlAddress; //完整地址  


        if (Objson.data) {
            Objson.data.code = Objson.code;
            Alldata = '?' + $http.UrlEncode(Objson.data);
        }

        if (type !== 'urlDeault') {
            type === 'urlADS' ? url = window.sessionStorage.productIP : url = window.sessionStorage.queryIP
        }

        httpUrlAddress = url + urlAddress
        fetch(`http://${httpUrlAddress}${Alldata}`, {
            method: 'get',
            mode: 'cors',
            headers: {
                "Authorization": authorizationToken,
            },
        }).then((res) => {
            console.log(res)
                // 如果http状态码正常,则直接返回数据
            if (res.status !== 200) {
                throw res.status
            } else {
                let Data;
                switch (Objson.dataType) {
                    case 'json':
                        {
                            Data = res.json()
                        }
                        break;

                    case 'text':
                        {
                            Data = res.test()
                        }
                        break;
                }
                return Data
            }
        }).then((res) => {
            res.errorCode = res.errorCode.toString(); //转成String类型
            if (res.errorCode !== '0') {
                message.error(res.errorMessage);
            }
            Objson.success.call(Nothis, res)
        }).catch((error) => {
            if (Objson.error) {
                Objson.error.call(Nothis, error)
            }
        });
    },
}

  

posted @ 2021-01-30 16:02  三行代码  阅读(1136)  评论(0编辑  收藏  举报