Skip to content
This repository has been archived by the owner on Jun 21, 2023. It is now read-only.

Commit

Permalink
Don't throw 500 error when Content-type is invalid (vercel#24818)
Browse files Browse the repository at this point in the history
Fixes vercel#24768

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
  • Loading branch information
vitalybaev committed May 5, 2021
1 parent 9b53be9 commit 6122db1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/next/next-server/server/api-utils.ts
Expand Up @@ -114,7 +114,12 @@ export async function parseBody(
req: NextApiRequest,
limit: string | number
): Promise<any> {
const contentType = parse(req.headers['content-type'] || 'text/plain')
let contentType
try {
contentType = parse(req.headers['content-type'] || 'text/plain')
} catch {
contentType = parse('text/plain')
}
const { type, parameters } = contentType
const encoding = parameters.charset || 'utf-8'

Expand Down
19 changes: 19 additions & 0 deletions test/integration/api-body-parser/test/index.test.js
Expand Up @@ -36,6 +36,13 @@ function runTests() {
expect(data).toEqual([{ title: 'Nextjs' }])
killApp(server)
})

it("should not throw if request's content-type is invalid", async () => {
await startServer()
const status = await makeRequestWithInvalidContentType()
expect(status).toBe(200)
killApp(server)
})
}

async function makeRequest() {
Expand All @@ -50,6 +57,18 @@ async function makeRequest() {
return data
}

async function makeRequestWithInvalidContentType() {
const status = await fetchViaHTTP(appPort, '/api', null, {
method: 'POST',
headers: {
'Content-Type': 'application/json;',
},
body: JSON.stringify([{ title: 'Nextjs' }]),
}).then((res) => res.status)

return status
}

const startServer = async (optEnv = {}, opts) => {
const scriptPath = join(appDir, 'server.js')
context.appPort = appPort = await getPort()
Expand Down

0 comments on commit 6122db1

Please sign in to comment.