0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 11:51:01 +01:00

fix(parseBody): return blank object when JSON body is nothing (#433)

Fix #428
This commit is contained in:
Yusuke Wada 2022-07-30 21:21:57 +09:00 committed by GitHub
parent bdcd536812
commit 4a2de0c1d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 2 deletions

View File

@ -41,7 +41,14 @@ describe('Parse Body Middleware', () => {
'Content-Type': 'text/plain',
},
})
console.log(res.headers.get('Content-Type'))
expect(await parseBody(res)).toEqual(payload)
})
it('should return blank object if JSON body is nothing', async () => {
const req = new Request('http://localhost/json', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
})
expect(await parseBody(req)).toEqual({})
})
})

View File

@ -4,7 +4,11 @@ export const parseBody = async (
const contentType = r.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
return await r.json()
let body = {}
try {
body = await r.json()
} catch {} // Do nothing
return body
} else if (contentType.includes('application/text')) {
return await r.text()
} else if (contentType.startsWith('text')) {