Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/better-fetch/src/test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,18 @@ describe("fetch", () => {
expect(data?.body).to.deep.eq(message);
});

it("stringifies body when content-type is explicitly application/json", async () => {
const payload = { foo: "bar" };
const { data } = await $echo<any>("/echo", {
method: "POST",
body: payload,
headers: { "Content-Type": "application/json" },
});

expect(data?.body).toEqual(payload);
expect(data?.headers).to.include({ "content-type": "application/json" });
});

it("Bypass URLSearchParams body", async () => {
const data = new URLSearchParams({ foo: "bar" });
const { data: res } = await betterFetch<any>(getURL("post"), {
Expand Down
7 changes: 6 additions & 1 deletion packages/better-fetch/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,12 @@ export function getBody(options?: BetterFetchOption) {
return null;
}
const headers = new Headers(options?.headers);
if (isJSONSerializable(options.body) && !headers.has("content-type")) {
const contentType = headers.get("content-type");
const isJSONContentType = contentType && JSON_RE.test(contentType);
if (
isJSONSerializable(options.body) &&
(!headers.has("content-type") || isJSONContentType)
) {
for (const [key, value] of Object.entries(options?.body)) {
if (value instanceof Date) {
options.body[key] = value.toISOString();
Expand Down