Skip to content

Commit

Permalink
Fix res.json support for string / null (#36186)
Browse files Browse the repository at this point in the history
Continuation of #33592 with updates tests / changes.

Co-Authored-By: Balázs Orbán <info@balazsorban.com>

Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
3 people committed Apr 15, 2022
1 parent e69820a commit 1582e11
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/next/server/api-utils/node.ts
Expand Up @@ -442,7 +442,7 @@ function sendJson(res: NextApiResponse, jsonBody: any): void {
res.setHeader('Content-Type', 'application/json; charset=utf-8')

// Use send to handle request
res.send(jsonBody)
res.send(JSON.stringify(jsonBody))
}

function isNotValidData(str: string): boolean {
Expand Down
3 changes: 3 additions & 0 deletions test/integration/api-support/pages/api/json-null.js
@@ -0,0 +1,3 @@
export default (req, res) => {
res.json(null)
}
3 changes: 3 additions & 0 deletions test/integration/api-support/pages/api/json-string.js
@@ -0,0 +1,3 @@
export default (req, res) => {
res.json('Hello world!')
}
18 changes: 17 additions & 1 deletion test/integration/api-support/test/index.test.js
Expand Up @@ -163,11 +163,27 @@ function runTests(dev = false) {
})

it('should support undefined response body', async () => {
const res = await fetchViaHTTP(appPort, '/api/undefined', null, {})
const res = await fetchViaHTTP(appPort, '/api/json-undefined', null, {})
const body = res.ok ? await res.text() : null
expect(body).toBe('')
})

it('should support string in JSON response body', async () => {
const res = await fetchViaHTTP(appPort, '/api/json-string', null, {})
const body = res.ok ? await res.text() : null
expect(body).toBe('"Hello world!"')
})

it('should support null in JSON response body', async () => {
const res = await fetchViaHTTP(appPort, '/api/json-null')
const body = res.ok ? await res.json() : 'Not null'
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe(
'application/json; charset=utf-8'
)
expect(body).toBe(null)
})

it('should return error with invalid JSON', async () => {
const data = await fetchViaHTTP(appPort, '/api/parse', null, {
method: 'POST',
Expand Down

0 comments on commit 1582e11

Please sign in to comment.