Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: only serialize JSON bodies #80

Merged
merged 2 commits into from
May 20, 2022
Merged
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
8 changes: 7 additions & 1 deletion src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,13 @@ export function createFetch (globalOptions: CreateFetchOptions): $Fetch {
}
if (ctx.options.body && isPayloadMethod(ctx.options.method)) {
if (isJSONSerializable(ctx.options.body)) {
ctx.options.body = JSON.stringify(ctx.options.body)
pi0 marked this conversation as resolved.
Show resolved Hide resolved
// Automatically JSON stringify request bodies, when not already a string.
ctx.options.body = typeof ctx.options.body === 'string'
? ctx.options.body
: JSON.stringify(ctx.options.body)

// Set Content-Type and Accept headers to application/json by default
// for JSON serializable request bodies.
ctx.options.headers = new Headers(ctx.options.headers)
if (!ctx.options.headers.has('content-type')) {
ctx.options.headers.set('content-type', 'application/json')
Expand Down
9 changes: 8 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { listen } from 'listhen'
import { getQuery, joinURL } from 'ufo'
import { createApp, useBody } from 'h3'
import { createApp, useBody, useRawBody } from 'h3'
import { Blob } from 'fetch-blob'
import { FormData } from 'formdata-polyfill/esm.min.js'
import { describe, beforeEach, afterEach, it, expect } from 'vitest'
Expand All @@ -20,6 +20,7 @@ describe('ohmyfetch', () => {
res.setHeader('Content-Type', 'application/octet-stream')
return new Blob(['binary'])
})
.use('/echo', async req => ({ body: await useRawBody(req) }))
listener = await listen(app)
})

Expand Down Expand Up @@ -73,6 +74,12 @@ describe('ohmyfetch', () => {
}
})

it('does not stringify body when content type != application/json', async () => {
const msg = '"Hallo von Pascal"'
const { body } = await $fetch(getURL('echo'), { method: 'POST', body: msg, headers: { 'Content-Type': 'text/plain' } })
expect(body).to.deep.eq(msg)
})

it('Bypass FormData body', async () => {
const data = new FormData()
data.append('foo', 'bar')
Expand Down