From 54ff3223b402b963baa189334587e2e590054276 Mon Sep 17 00:00:00 2001 From: Vitaly Baev Date: Wed, 5 May 2021 17:27:44 +0300 Subject: [PATCH] Don't throw 500 error when Content-type is invalid (#24818) Fixes #24768 ## Bug - [x] Related issues linked using `fixes #number` - [x] Integration tests added --- packages/next/next-server/server/api-utils.ts | 7 ++++++- .../api-body-parser/test/index.test.js | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/next/next-server/server/api-utils.ts b/packages/next/next-server/server/api-utils.ts index da33727430bb..350a87dac212 100644 --- a/packages/next/next-server/server/api-utils.ts +++ b/packages/next/next-server/server/api-utils.ts @@ -114,7 +114,12 @@ export async function parseBody( req: NextApiRequest, limit: string | number ): Promise { - 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' diff --git a/test/integration/api-body-parser/test/index.test.js b/test/integration/api-body-parser/test/index.test.js index ea90f43bdbcf..c9a9b7200d31 100644 --- a/test/integration/api-body-parser/test/index.test.js +++ b/test/integration/api-body-parser/test/index.test.js @@ -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() { @@ -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()