Skip to content

Commit ec12ab9

Browse files
committed
fix: allow empty json body
The json middleware crashes when it receives an empty string from req.chunk This causes JSON.parse() to throw an exception since it does not accept empty strings
1 parent d4b29a4 commit ec12ab9

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ const custom =
3636

3737
const json = () => async (req: ReqWithBody, res: Response, next: NextFunction) => {
3838
if (hasBody(req.method)) {
39-
req.body = await p((x) => JSON.parse(x.toString()))(req, res, next)
39+
req.body = await p((x) => x ? JSON.parse(x.toString()) : {})(req, res, next)
4040
next()
4141
} else next()
4242
}

test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,25 @@ test('should parse JSON body', async () => {
2222
}).expect(200, { hello: 'world' })
2323
})
2424

25+
test('should ignore JSON empty body', async () => {
26+
const server = createServer(async (req: ReqWithBody, res) => {
27+
await json()(req, res, (err) => void err && console.log(err))
28+
29+
res.setHeader('Content-Type', 'application/json')
30+
31+
res.end(JSON.stringify({ok: true}));
32+
})
33+
34+
await makeFetch(server)('/', {
35+
body: '',
36+
method: 'POST',
37+
headers: {
38+
Accept: 'application/json',
39+
'Content-Type': 'application/json',
40+
},
41+
}).expect(200, { ok: true })
42+
})
43+
2544
test('should parse json body with no content-type headers', async () => {
2645
const server = createServer(async (req: ReqWithBody, res) => {
2746
await json()(req, res, (err) => void err && console.log(err))

0 commit comments

Comments
 (0)