/** @format */ import {Log} from '../utils/LogUtils' import {Data, Mgr} from '../GameControl' import {LANGUAGE_TYPE} from '../enums/Enum' export interface IHttpReq { url: string method: 'POST' | 'GET' success: (data: any) => void fail?: (data?: any) => void data?: any type?: 'text' | 'arraybuffer' contentType?: 'application/json' | 'text/plain' | 'application/x-www-form-urlencoded' err?: () => void timeout?: () => void } export class HttpManager { request({url, method, success, fail, data, type = 'text', err, timeout, contentType}: IHttpReq) { Log.net('requestUrl--->', url) url = encodeURI(url) let successCB = res => { if (res.code != undefined) { if (res.code == 0) { success && success(res) } else { fail && fail(res) Mgr.ui.tip(res.code + ':' + res.msg) } } else { success && success(res) } } if (cc.sys.isBrowser || cc.sys.isNative) { let xhr = new XMLHttpRequest() try { xhr.open(method, url, true) if (data) { Log.net('requestData--->', data) } if (!contentType) { if (data) { if (typeof data == 'object') { contentType = 'application/json' } else { contentType = 'text/plain' } } else { contentType = 'application/x-www-form-urlencoded' } } xhr.setRequestHeader('Content-Type', contentType) xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { let response if (type == 'text') { response = xhr.responseText if (response == '') { response = '{}' } try { response = JSON.parse(response) } catch (e) {} Log.net('responseData--->url:' + url + '--->', response) successCB(response) } else if (type == 'arraybuffer') { response = xhr.response try { successCB(response) } catch (e) { cc.log(e) } } } else { Log.net('http request status---->', xhr.status, '---->', url) Mgr.ui.tip(Mgr.i18n.getLabel(LANGUAGE_TYPE.httpFail, [xhr.status])) if (fail) fail() } } } xhr.responseType = type if (data && typeof data == 'object') { data = JSON.stringify(data) } xhr.onerror = data => { Log.net('http request onerror---->', data) if (err) err() } xhr.timeout = 15000 xhr.ontimeout = () => { Log.net('http request timeout---->', url) if (timeout) { timeout() } else { Mgr.ui.tip(LANGUAGE_TYPE.httpTimeout) } } xhr.send(data) } catch (e) { Log.net('http request err---->', e) } } } }