From 12ab795ec6e8c16030315df98a005ece762fdc18 Mon Sep 17 00:00:00 2001 From: Nariman Movffaghi Date: Tue, 16 Nov 2021 13:00:56 +0330 Subject: [PATCH 1/2] fix(fetch): json header for posts with array of objects body --- src/fetch.ts | 2 +- test/index.test.mjs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/fetch.ts b/src/fetch.ts index c3881d9..04c2dbe 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -77,7 +77,7 @@ export function createFetch ({ fetch }: CreateFetchOptions): $Fetch { request = withQuery(request, opts.params) } const hasPayload = payloadMethods.includes((opts.method || '').toLowerCase()) - if (opts.body && opts.body.toString() === '[object Object]' && hasPayload) { + if (opts.body && opts.body.toString().includes('[object Object]') && hasPayload) { opts.body = JSON.stringify(opts.body) setHeader(opts, 'content-type', 'application/json') } diff --git a/test/index.test.mjs b/test/index.test.mjs index 99bdee3..165f78d 100644 --- a/test/index.test.mjs +++ b/test/index.test.mjs @@ -41,6 +41,9 @@ describe('ohmyfetch', () => { const { body } = await $fetch(getURL('post'), { method: 'POST', body: { num: 42 } }) expect(body).to.deep.eq({ num: 42 }) + const body2 = (await $fetch(getURL('post'), { method: 'POST', body: [{ num: 42 }, { num: 43 }] })).body + expect(body2).to.deep.eq([{ num: 42 }, { num: 43 }]) + const headerFetches = [ [['Content-Type', 'text/html']], [], From 3899d4c1d55d30664d0d8eceae22b790bd90c0bd Mon Sep 17 00:00:00 2001 From: Nariman Movffaghi Date: Tue, 16 Nov 2021 20:39:08 +0330 Subject: [PATCH 2/2] refactor(fetch): auto json content type based on body option --- src/fetch.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fetch.ts b/src/fetch.ts index 04c2dbe..0e8fc5b 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -77,7 +77,7 @@ export function createFetch ({ fetch }: CreateFetchOptions): $Fetch { request = withQuery(request, opts.params) } const hasPayload = payloadMethods.includes((opts.method || '').toLowerCase()) - if (opts.body && opts.body.toString().includes('[object Object]') && hasPayload) { + if (opts.body && typeof opts.body === 'object' && hasPayload) { opts.body = JSON.stringify(opts.body) setHeader(opts, 'content-type', 'application/json') }