Skip to content

Commit

Permalink
docs(validators): content-type is required on requests with json vali…
Browse files Browse the repository at this point in the history
…dators (honojs#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
  • Loading branch information
Soviut authored Nov 29, 2024
1 parent 06c7f18 commit a471fa1
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions docs/guides/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,53 @@ 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).
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', {
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.
Expand Down

0 comments on commit a471fa1

Please sign in to comment.