Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(validators): content-type is required on requests with json validators #540

Merged
merged 2 commits into from
Nov 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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', {
Soviut marked this conversation as resolved.
Show resolved Hide resolved
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