Skip to content

Commit 819cc3f

Browse files
tsusderegr2m
andauthored
fix: avoid Unexpected end of JSON input when response body is empty (#648)
Fixes #649 Co-authored-by: Gregor Martynus <[email protected]>
1 parent 5c1fcdf commit 819cc3f

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

Diff for: src/fetch-wrapper.ts

+11-1
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,17 @@ export default function fetchWrapper(
153153
async function getResponseData(response: Response) {
154154
const contentType = response.headers.get("content-type");
155155
if (/application\/json/.test(contentType!)) {
156-
return response.json();
156+
return (
157+
response
158+
.json()
159+
// In the event that we get an empty response body we fallback to
160+
// using .text(), but this should be investigated since if this were
161+
// to occur in the GitHub API it really should not return an empty body.
162+
.catch(() => response.text())
163+
// `node-fetch` is throwing a "body used already for" error if `.text()` is run
164+
// after a failed .json(). To account for that we fallback to an empty string
165+
.catch(() => "")
166+
);
157167
}
158168

159169
if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {

Diff for: test/request.test.ts

+26
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,32 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
400400
);
401401
});
402402

403+
it("error response with no body (octokit/request.js#649)", () => {
404+
const mock = fetchMock
405+
.sandbox()
406+
.get("path:/repos/octokit-fixture-org/hello-world/contents/README.md", {
407+
status: 500,
408+
body: undefined,
409+
headers: {
410+
"content-type": "application/json",
411+
},
412+
});
413+
414+
return request("GET /repos/{owner}/{repo}/contents/{path}", {
415+
headers: {
416+
accept: "content-type: application/json",
417+
},
418+
owner: "octokit-fixture-org",
419+
repo: "hello-world",
420+
path: "README.md",
421+
request: {
422+
fetch: mock,
423+
},
424+
}).catch((error) => {
425+
expect(error.response.data).toEqual("");
426+
});
427+
});
428+
403429
it("non-JSON response", () => {
404430
const mock = fetchMock
405431
.sandbox()

0 commit comments

Comments
 (0)