diff --git a/src/protocols/Http.ts b/src/protocols/Http.ts index bcc86fed6..fcdeadaf4 100644 --- a/src/protocols/Http.ts +++ b/src/protocols/Http.ts @@ -1,9 +1,9 @@ "use strict"; -import staticHttpRoutes from "./routes.json"; -import { KuzzleAbstractProtocol } from "./abstract/Base"; import { HttpRoutes, JSONObject } from "../types"; import { RequestPayload } from "../types/RequestPayload"; +import { KuzzleAbstractProtocol } from "./abstract/Base"; +import staticHttpRoutes from "./routes.json"; /** * Http protocol used to connect to a Kuzzle server. @@ -405,6 +405,11 @@ export default class HttpProtocol extends KuzzleAbstractProtocol { ); } + const contentType = response.headers["content-type"]; + if (!contentType || !contentType.includes("application/json")) { + return response.body; + } + return JSON.parse(response.body); }); } @@ -435,6 +440,11 @@ export default class HttpProtocol extends KuzzleAbstractProtocol { xhr.onload = () => { try { + const contentType = xhr.getResponseHeader("Content-Type"); + if (!contentType || !contentType.includes("application/json")) { + resolve(xhr.responseText); + return; + } const json = JSON.parse(xhr.responseText); resolve(json); } catch (err) { diff --git a/test/protocol/Http.test.js b/test/protocol/Http.test.js index bdad64c42..00ead9347 100644 --- a/test/protocol/Http.test.js +++ b/test/protocol/Http.test.js @@ -677,9 +677,12 @@ describe("HTTP networking module", () => { let httpRequestStub; beforeEach(() => { - httpRequestStub = sinon - .stub() - .resolves({ body: JSON.stringify(mockResponseBody) }); + httpRequestStub = sinon.stub().resolves({ + body: JSON.stringify(mockResponseBody), + headers: { + "content-type": "application/json", + }, + }); const { default: MockHttp } = proxyquire("../../src/protocols/Http", { "min-req-promise": { request: httpRequestStub }, @@ -793,6 +796,7 @@ describe("HTTP networking module", () => { open: sinon.stub(), send: sinon.stub(), setRequestHeader: sinon.stub(), + getResponseHeader: sinon.stub().returns("application/json"), onreadystatechange: sinon.stub(), timeout: 0, };