From c13c4aefca2b79ace4c29191d5204d2e2bbb4793 Mon Sep 17 00:00:00 2001 From: MiaoWoo Date: Sun, 23 Feb 2020 22:33:51 +0800 Subject: [PATCH] fix: some bug at xhr and console Signed-off-by: MiaoWoo --- packages/api/src/console.ts | 2 +- packages/common/src/http.ts | 7 +++++-- packages/ployfill/src/xml-http-request.ts | 21 +++++++++++---------- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/packages/api/src/console.ts b/packages/api/src/console.ts index da5f998b..5f33ffe3 100644 --- a/packages/api/src/console.ts +++ b/packages/api/src/console.ts @@ -80,7 +80,7 @@ export class MiaoScriptConsole implements Console { } object(obj) { for (var i in obj) { - this.logger(i, '=>', obj[i]) + this.info(i, '=>', obj[i]) } } ex(ex: Error) { diff --git a/packages/common/src/http.ts b/packages/common/src/http.ts index cade1e78..2d75ce22 100644 --- a/packages/common/src/http.ts +++ b/packages/common/src/http.ts @@ -24,8 +24,11 @@ function request(config: RequestConfig) { for (const header in config.headers) { xhr.setRequestHeader(header, config.headers[header]); } - let future = xhr.send(config.data); - return future.get(); + xhr.send(config.data); + if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) { + xhr.responseType = "json" + } + return xhr.get(); } function _proxy(method: Method) { diff --git a/packages/ployfill/src/xml-http-request.ts b/packages/ployfill/src/xml-http-request.ts index caad054e..2222f2c9 100644 --- a/packages/ployfill/src/xml-http-request.ts +++ b/packages/ployfill/src/xml-http-request.ts @@ -114,7 +114,7 @@ export class XMLHttpRequest { return this._statusText; } get response() { - return JSON.parse(this._response); + return this._response ? JSON.parse(this._response) : this._response; } get responseText() { return this._response; @@ -174,6 +174,16 @@ export class XMLHttpRequest { if (!this._async) { future.get() } return future; } + get() { + switch (this._responseType) { + case "json": + return this.response; + case "text": + return this.responseText; + default: + throw Error(`Unsupport ResponseType: ${this._responseType} !`) + } + } abort() { this._connection.disconnect(); this.onabort(); @@ -182,7 +192,6 @@ export class XMLHttpRequest { private _send(body?: string | object) { try { this._connection.connect(); - this.onloadstart(); if (body) { let bodyType = Object.prototype.toString.call(body); @@ -204,14 +213,6 @@ export class XMLHttpRequest { this._response = this.readOutput(this._connection.getErrorStream()); } this.onloadend(); - switch (this._responseType) { - case "json": - return this.response; - case "text": - return this.responseText; - default: - throw Error(`Unsupport ResponseType: ${this._responseType} !`) - } } catch (ex) { if (ex instanceof SocketTimeoutException && this.ontimeout) { return this.ontimeout(ex)