Skip to content

Commit 1a4ce48

Browse files
authored
fix: normalize options.headers (again) after onRequest hook (#524)
1 parent 47fe807 commit 1a4ce48

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/fetch.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,11 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
114114

115115
if (context.options.onRequest) {
116116
await callHooks(context, context.options.onRequest);
117+
if (!(context.options.headers instanceof Headers)) {
118+
context.options.headers = new Headers(
119+
context.options.headers || {} /* compat */
120+
);
121+
}
117122
}
118123

119124
if (typeof context.request === "string") {
@@ -148,8 +153,6 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
148153

149154
// Set Content-Type and Accept headers to application/json by default
150155
// for JSON serializable request bodies.
151-
// Pass empty object as older browsers don't support undefined.
152-
context.options.headers = new Headers(context.options.headers || {});
153156
if (!contentType) {
154157
context.options.headers.set("content-type", "application/json");
155158
}

test/index.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,30 @@ describe("ofetch", () => {
468468
).rejects.toThrow("error in onResponseError");
469469
});
470470

471+
it("hook modifications", async () => {
472+
// onRequest
473+
expect(
474+
await $fetch(getURL("/echo"), {
475+
method: "POST",
476+
body: { num: 42 },
477+
onRequest(ctx) {
478+
ctx.options.headers = new Headers({ "x-foo": "bar" });
479+
},
480+
}).then((r) => r.headers)
481+
).toMatchObject({ "x-foo": "bar" });
482+
483+
expect(
484+
await $fetch(getURL("/echo"), {
485+
method: "POST",
486+
body: { num: 42 },
487+
onRequest(ctx) {
488+
// @ts-expect-error backwards compatibility (with warnings) for object headers
489+
ctx.options.headers = { "x-foo": "bar" };
490+
},
491+
}).then((r) => r.headers)
492+
).toMatchObject({ "x-foo": "bar" });
493+
});
494+
471495
it("calls hooks", async () => {
472496
const onRequest = vi.fn();
473497
const onRequestError = vi.fn();

0 commit comments

Comments
 (0)