Skip to content

Commit 9becea5

Browse files
committed
fix(http): fix empty raw responses parsed as json
1 parent e4bdf50 commit 9becea5

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/protocols/Http.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
"use strict";
22

3-
import staticHttpRoutes from "./routes.json";
4-
import { KuzzleAbstractProtocol } from "./abstract/Base";
53
import { HttpRoutes, JSONObject } from "../types";
64
import { RequestPayload } from "../types/RequestPayload";
5+
import { KuzzleAbstractProtocol } from "./abstract/Base";
6+
import staticHttpRoutes from "./routes.json";
77

88
/**
99
* Http protocol used to connect to a Kuzzle server.
@@ -405,6 +405,11 @@ export default class HttpProtocol extends KuzzleAbstractProtocol {
405405
);
406406
}
407407

408+
const contentType = response.headers["content-type"];
409+
if (!contentType || !contentType.includes("application/json")) {
410+
return response.body;
411+
}
412+
408413
return JSON.parse(response.body);
409414
});
410415
}
@@ -435,6 +440,11 @@ export default class HttpProtocol extends KuzzleAbstractProtocol {
435440

436441
xhr.onload = () => {
437442
try {
443+
const contentType = xhr.getResponseHeader("Content-Type");
444+
if (!contentType || !contentType.includes("application/json")) {
445+
resolve(xhr.responseText);
446+
return;
447+
}
438448
const json = JSON.parse(xhr.responseText);
439449
resolve(json);
440450
} catch (err) {

test/protocol/Http.test.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -677,9 +677,12 @@ describe("HTTP networking module", () => {
677677
let httpRequestStub;
678678

679679
beforeEach(() => {
680-
httpRequestStub = sinon
681-
.stub()
682-
.resolves({ body: JSON.stringify(mockResponseBody) });
680+
httpRequestStub = sinon.stub().resolves({
681+
body: JSON.stringify(mockResponseBody),
682+
headers: {
683+
"content-type": "application/json",
684+
},
685+
});
683686

684687
const { default: MockHttp } = proxyquire("../../src/protocols/Http", {
685688
"min-req-promise": { request: httpRequestStub },
@@ -793,6 +796,7 @@ describe("HTTP networking module", () => {
793796
open: sinon.stub(),
794797
send: sinon.stub(),
795798
setRequestHeader: sinon.stub(),
799+
getResponseHeader: sinon.stub().returns("application/json"),
796800
onreadystatechange: sinon.stub(),
797801
timeout: 0,
798802
};

0 commit comments

Comments
 (0)