Skip to content

Commit a471fa1

Browse files
authored
docs(validators): content-type is required on requests with json validators (#540)
* docs: content-type is required on requests with json validators Added example when testing using app.request() which is what originally tripped me up. * Added example app to warning
1 parent 06c7f18 commit a471fa1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

docs/guides/validation.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,53 @@ Within the handler you can get the validated value with `c.req.valid('form')`.
5050
5151
Validation targets include `json`, `query`, `header`, `param` and `cookie` in addition to `form`.
5252
53+
::: warning
54+
When you validate `json`, the request _must_ contain a `Content-Type: application/json` header
55+
otherwise the request body will not be parsed and you will invalid JSON errors.
56+
57+
It is important to set the `content-type` header when testing using
58+
[`app.request()`](../api/request.md).
59+
60+
If you had an app set up like this.
61+
62+
```ts
63+
const app = new Hono()
64+
app.get(
65+
'/testing',
66+
validator('json', (value, c) => {
67+
// pass-through validator
68+
return value
69+
}),
70+
(c) => {
71+
const body = c.req.valid('json')
72+
return c.json(body)
73+
}
74+
)
75+
```
76+
And your tests were set up like this.
77+
```ts
78+
// ❌ this will not work
79+
const res = await app.request('/testing', {
80+
method: 'POST',
81+
body: JSON.stringify({ key: 'value' }),
82+
})
83+
const data = await res.json()
84+
console.log(data) // undefined
85+
```
86+
87+
```ts
88+
// ✅ this will work
89+
const res = await app.request('/testing', {
90+
method: 'POST',
91+
body: JSON.stringify({ key: 'value' }),
92+
headers: new Headers({ 'Content-Type': 'application/json' }),
93+
})
94+
const data = await res.json()
95+
console.log(data) // { key: 'value' }
96+
```
97+
98+
:::
99+
53100
::: warning
54101
When you validate `header`, you need to use **lowercase** name as the key.
55102

0 commit comments

Comments
 (0)