From 6d00a4f26abb730f2df18d53e7157a4949bb5e3b Mon Sep 17 00:00:00 2001 From: Soviut Date: Wed, 27 Nov 2024 22:04:54 -0500 Subject: [PATCH 1/2] docs: content-type is required on requests with json validators Added example when testing using app.request() which is what originally tripped me up. --- docs/guides/validation.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/guides/validation.md b/docs/guides/validation.md index 79dc442e..0d86b330 100644 --- a/docs/guides/validation.md +++ b/docs/guides/validation.md @@ -50,6 +50,36 @@ Within the handler you can get the validated value with `c.req.valid('form')`. Validation targets include `json`, `query`, `header`, `param` and `cookie` in addition to `form`. +::: warning +When you validate `json`, the request _must_ contain a `Content-Type: application/json` header +otherwise the request body will not be parsed and you will invalid JSON errors. + +It is important to set the `content-type` header when testing using +[`app.request()`](../api/request.md). + +```ts +// ❌ this will not work +const res = await app.request('/testing', { + method: 'POST', + body: JSON.stringify({ key: 'value' }), +}) +const data = await res.json() +console.log(data) // undefined +``` + +```ts +// ✅ this will work +const res = await app.request('/testing', { + method: 'POST', + body: JSON.stringify({ key: 'value' }), + headers: new Headers({ 'Content-Type': 'application/json' }), +}) +const data = await res.json() +console.log(data) // { key: 'value' } +``` + +::: + ::: warning When you validate `header`, you need to use **lowercase** name as the key. From bfa26869671150bac038ba887cfd5952a57259db Mon Sep 17 00:00:00 2001 From: Soviut Date: Fri, 29 Nov 2024 04:05:15 -0500 Subject: [PATCH 2/2] Added example app to warning --- docs/guides/validation.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/guides/validation.md b/docs/guides/validation.md index 0d86b330..93d3b326 100644 --- a/docs/guides/validation.md +++ b/docs/guides/validation.md @@ -57,6 +57,23 @@ otherwise the request body will not be parsed and you will invalid JSON errors. It is important to set the `content-type` header when testing using [`app.request()`](../api/request.md). +If you had an app set up like this. + +```ts +const app = new Hono() +app.get( + '/testing', + validator('json', (value, c) => { + // pass-through validator + return value + }), + (c) => { + const body = c.req.valid('json') + return c.json(body) + } +) +``` +And your tests were set up like this. ```ts // ❌ this will not work const res = await app.request('/testing', {