错误:服务器操作要求将请求体解析为 FormData 或 JSON。收到意外的内容类型:application/x-www-form-urlencoded
Error: Server Actions require the request body to be parsed as FormData or JSON. Received unexpected content type: application/x-www-form-urlencoded
ID: nextjs/server-action-formdata-encoding
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 14.2.0 | active | — | — | — |
| 15.0.0 | active | — | — | — |
| 14.2.15 | active | — | — | — |
根因分析
服务器操作以非标准内容类型(例如 application/x-www-form-urlencoded)被调用,而非 multipart/form-data 或 application/json。这通常发生在通过 fetch 手动提交表单而未设置正确标头时。
English
A Server Action is called with a non-standard content type (e.g., application/x-www-form-urlencoded) instead of multipart/form-data or application/json. This typically happens when submitting a form manually via fetch without proper headers.
官方文档
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions解决方案
-
Use the native form action attribute with a Server Action function directly, which automatically handles proper encoding.
-
If calling from JavaScript, use FormData object and avoid setting Content-Type header (let the browser set it automatically).
无效尝试
常见但无效的做法:
-
Adding 'Content-Type: multipart/form-data' manually without FormData
85% 失败
The content type must match the actual body format. Sending multipart/form-data with a JSON string body still fails because the server expects FormData parsing.
-
Setting enctype attribute on the HTML form to 'application/json'
90% 失败
HTML forms natively only support application/x-www-form-urlencoded, multipart/form-data, and text/plain. application/json is not valid for form submission.
-
Using JSON.stringify on FormData before sending
95% 失败
FormData cannot be serialized with JSON.stringify. You must send the FormData object directly as the body.