Skip to content

Commit 7ef500f

Browse files
author
v 1 r t l
authored
Merge pull request #20 from fernando7jr/master
fix: allow empty json body
2 parents d4b29a4 + 759fd6a commit 7ef500f

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-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: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,35 @@ 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+
// Empty string body
35+
await makeFetch(server)('/', {
36+
body: '',
37+
method: 'POST',
38+
headers: {
39+
Accept: 'application/json',
40+
'Content-Type': 'application/json',
41+
},
42+
}).expect(200, { ok: true })
43+
44+
// Unset body
45+
await makeFetch(server)('/', {
46+
method: 'POST',
47+
headers: {
48+
Accept: 'application/json',
49+
'Content-Type': 'application/json',
50+
},
51+
}).expect(200, { ok: true })
52+
})
53+
2554
test('should parse json body with no content-type headers', async () => {
2655
const server = createServer(async (req: ReqWithBody, res) => {
2756
await json()(req, res, (err) => void err && console.log(err))

0 commit comments

Comments
 (0)