http封装类

哪位大佬有封装好的http工具类啊,万分感谢

不知道 fetch 能不能用,,

百度一下不好了

用不了。。。。

fetch能用,然后你可以引入axios

可以看看我这个:https://gitee.com/friend-z/internationalization-demo.git

你看下,有 bug 我不管,,

export default class HttpMgr {
	public static request(url: string, args?: any, isPost?: boolean, retJson?: boolean) {
		return new Promise<string|any>((resolve, reject) => {
			const xhr = cc.loader.getXMLHttpRequest();

			xhr.timeout = 10000;
			xhr.ontimeout = () => {
				reject('timeout! url:' + url + ' 请求超时');
			}
			xhr.onerror = () => {
				reject('error! url:' + url + ',statusText:' + xhr.statusText);
			};
			xhr.onreadystatechange = () => {
				if (xhr.readyState == 4) {
					if (xhr.status >= 200 && xhr.status < 400) {
						let res = xhr.responseText;
						if (retJson) {
							res = JSON.parse(res);
						}
						resolve(res);
					} else {
						reject('bad status! url:' + url + ',status:' + xhr.status + ',statusText:' + xhr.statusText);
					}
				}
			}

			var httpParams = this.dict2HttpParams(args);

			if (!isPost) {
				url = httpParams == '' ? url : url + '?' + httpParams;
				xhr.open("GET", url, true);
				xhr.send();
			} else {
				xhr.open("POST", url, true);
				xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xhr.send(httpParams);
			}
		});
	}


	public static request2(url: string, caller?: any, callback?: Function, args?: any, isPost?: boolean, retJson?: boolean): void {
		const xhr = new XMLHttpRequest();

		xhr.timeout = 10000;
		xhr.ontimeout = () => {
			this.doCallback(caller, callback, '请求超时');
		}
		xhr.onerror = () => {
			this.doCallback(caller, callback, 'error! url:' + url + ',statusText:' + xhr.statusText);
		};
		xhr.onreadystatechange = () => {
			if (xhr.readyState == 4) {
				if (xhr.status >= 200 && xhr.status < 400) {
					let res = xhr.responseText;
					if (retJson) {
						res = JSON.parse(res);
					}
					this.doCallback(caller, callback, '', res);
				} else {
					this.doCallback(caller, callback, '(error) readyState: ' + xhr.readyState + ' status: ' + xhr.status);
				}
			}
		}

		var httpParams = this.dict2HttpParams(args);

		if (!isPost) {
			url = httpParams == '' ? url : url + '?' + httpParams;
			xhr.open("GET", url, true);
			xhr.send();
		} else {
			xhr.open("POST", url, true);
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xhr.send(httpParams);
		}
	}


	private static dict2HttpParams(dict: { [x: string]: string; }): string {
		if (!dict) return '';

		let content = '';
		for (const key in dict) content += key + '=' + dict[key] + '&';

		return content.substr(0, content.length - 1);
	}

	private static doCallback(caller?: any, callback?: Function, errMsg?: string, response?: any): void {
		if (caller) {
			callback.apply(caller, [errMsg, response]);
		} else {
			callback(errMsg, response);
		}
	}
}

好的,多谢

我试试哈。。

fetch 能用是最好的,,