Skip to content

Commit

Permalink
fix: skip reading body with 204 responses and HEAD requests (reso…
Browse files Browse the repository at this point in the history
…lves #171) (resolves #84)
  • Loading branch information
pi0 committed Aug 23, 2023
1 parent 458d161 commit 9e20440
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
28 changes: 16 additions & 12 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
14 changes: 14 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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_
Expand Down

0 comments on commit 9e20440

Please sign in to comment.