diff --git a/src/routes/api/contact.ts b/src/routes/api/contact.ts index 8e20e62..f4d020a 100644 --- a/src/routes/api/contact.ts +++ b/src/routes/api/contact.ts @@ -35,7 +35,7 @@ export const DEFAULT_HEADERS = { } as const export class Handler { - #allowedContentTypes = ['application/json'] + #allowedContentType = 'application/x-www-form-urlencoded' #allowedMethods = ['POST'] #storage: RecordStorage @@ -103,7 +103,7 @@ export class Handler { if (!this.#validateContentType(request)) return new Response( JSON.stringify({ - allowedContentType: 'application/json', + allowedContentType: this.#allowedContentType, contentType: request.headers.get('Content-Type'), error: 'Invalid Content-Type header.', status: 400, @@ -118,10 +118,17 @@ export class Handler { }, ) - let body: Record<(typeof this.requiredFields)[number], string> + let body: Record try { - body = await request.json() + body = [...(await request.formData()).entries()].reduce( + (record, [key, value]) => { + return { ...record, [key]: value } + }, + {}, + ) + + if (Object.keys(body).length === 0) throw new Error('invalid body') } catch (error) { console.error(error) return this.#getResponse(this.responseData.invalidBody) @@ -208,9 +215,7 @@ export class Handler { * @since unreleased */ #validateContentType(request: Request): boolean { - return this.#allowedContentTypes.includes( - `${request.headers.get('Content-Type')}`, - ) + return this.#allowedContentType === request.headers.get('Content-Type') } /** diff --git a/tests/unit/routes/api/contact.test.ts b/tests/unit/routes/api/contact.test.ts index d618f45..4ee1cd7 100644 --- a/tests/unit/routes/api/contact.test.ts +++ b/tests/unit/routes/api/contact.test.ts @@ -80,7 +80,7 @@ describe(PATH, () => { const headers = new Headers({ Origin: site.origin }) describe.each([ - 'application/x-www-form-urlencoded', + 'application/json', 'multipart/form-data', 'text/html', 'text/plain', @@ -119,10 +119,10 @@ describe(PATH, () => { ) }) - describe('when Content-Type header is application/json', () => { - headers.set('Content-Type', 'application/json') + describe('when Content-Type header is application/x-www-form-urlencoded', () => { + headers.set('Content-Type', 'application/x-www-form-urlencoded') - describe('when a valid json body is not provided', () => { + describe('when a body is not provided', () => { const request = new Request(ROUTE, { headers, method }) const consoleError = console.error @@ -195,7 +195,7 @@ describe(PATH, () => { }) describe('when all required fields are valid', () => { - const body = JSON.stringify({ + const body = new URLSearchParams({ email: 'example@example.com', message: 'This is an example message.', name: 'Example',