From 9e204400c64917b8b5fe7214b4bf0730cb5f5f3e Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 23 Aug 2023 14:16:06 +0200 Subject: [PATCH] fix: skip reading body with `204` responses and `HEAD` requests (resolves #171) (resolves #84) --- src/fetch.ts | 28 ++++++++++++++++------------ test/index.test.ts | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/fetch.ts b/src/fetch.ts index 61bf702b..482a061b 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -213,19 +213,23 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch { return await onError(context); } - const responseType = - (context.options.parseResponse ? "json" : context.options.responseType) || - detectResponseType(context.response.headers.get("content-type") || ""); + if (context.response.body) { + const responseType = + (context.options.parseResponse + ? "json" + : context.options.responseType) || + detectResponseType(context.response.headers.get("content-type") || ""); - // We override the `.json()` method to parse the body more securely with `destr` - if (responseType === "json") { - const data = await context.response.text(); - const parseFunction = context.options.parseResponse || destr; - context.response._data = parseFunction(data); - } else if (responseType === "stream") { - context.response._data = context.response.body; - } else { - context.response._data = await context.response[responseType](); + // We override the `.json()` method to parse the body more securely with `destr` + if (responseType === "json") { + const data = await context.response.text(); + const parseFunction = context.options.parseResponse || destr; + context.response._data = parseFunction(data); + } else if (responseType === "stream") { + context.response._data = context.response.body; + } else { + context.response._data = await context.response[responseType](); + } } if (context.options.onResponse) { diff --git a/test/index.test.ts b/test/index.test.ts index ae7151d3..a75250a4 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -66,6 +66,10 @@ describe("ofetch", () => { "/408", eventHandler(() => createError({ status: 408 })) ) + .use( + "/204", + eventHandler(() => null) // eslint-disable-line unicorn/no-null + ) .use( "/timeout", eventHandler(async () => { @@ -204,6 +208,16 @@ describe("ofetch", () => { expect(res?.statusMessage).to.eq("Forbidden"); }); + it("204 no content", async () => { + const res = await $fetch(getURL("204")); + expect(res).toBeUndefined(); + }); + + it("HEAD no content", async () => { + const res = await $fetch(getURL("/ok"), { method: "HEAD" }); + expect(res).toBeUndefined(); + }); + it("baseURL with retry", async () => { const error = await $fetch("", { baseURL: getURL("404"), retry: 3 }).catch( (error_) => error_