Unverified Commit a0ea5f2d authored by Vu Van Dung's avatar Vu Van Dung Committed by GitHub

Fix formData code snippet in route handler docs (#52532)



### Why?

The code snippet in the Route handler `formData` documentation

```ts
import { NextResponse } from 'next/server'
 
export async function POST(request: Request) {
  const formData = await request.formData()
  return NextResponse.json({ formData })
}
```

is slightly wrong, because `formData` is not a plain object and hence `return NextResponse.json({ formData })` doesn't actually work.

Since we are already in the topic of parsing `formData`, I also added a mention on `zod-form-data` which can be used to validate the form and parse it to non-string formats such as `number`.
parent 78432049
......@@ -553,7 +553,9 @@ import { NextResponse } from 'next/server'
export async function POST(request: Request) {
const formData = await request.formData()
return NextResponse.json({ formData })
const name = formData.get('name')
const email = formData.get('email')
return NextResponse.json({ name, email })
}
```
......@@ -562,10 +564,14 @@ import { NextResponse } from 'next/server'
export async function POST(request) {
const formData = await request.formData()
return NextResponse.json({ formData })
const name = formData.get('name')
const email = formData.get('email')
return NextResponse.json({ name, email })
}
```
Since `formData` data are all strings, you may want to use [`zod-form-data`](https://www.npmjs.com/zod-form-data) to validate the request and retrieve data in the format you prefer (e.g. `number`).
### CORS
You can set CORS headers on a `Response` using the standard Web API methods:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment