Fix res.json support for string / null (#36186)

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>
This commit is contained in:
Tim Neutkens 2022-04-15 16:04:00 +02:00 committed by GitHub
parent e69820accc
commit 1582e11185
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 24 additions and 2 deletions

View file

@ -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 {

View file

@ -0,0 +1,3 @@
export default (req, res) => {
res.json(null)
}

View file

@ -0,0 +1,3 @@
export default (req, res) => {
res.json('Hello world!')
}

View file

@ -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',