Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix res.json support for string / null #36186

Merged
merged 2 commits into from Apr 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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