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:
parent
bdcd536812
commit
4a2de0c1d1
@ -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({})
|
||||
})
|
||||
})
|
||||
|
@ -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')) {
|
||||
|
Loading…
Reference in New Issue
Block a user