nextjs protocol_error ai_generated true

错误:服务器操作要求将请求体解析为 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

其他格式: JSON · Markdown 中文 · English
92%修复率
88%置信度
1证据数
2024-06-10首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

官方文档

https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions

解决方案

  1. Use the native form action attribute with a Server Action function directly, which automatically handles proper encoding.
  2. If calling from JavaScript, use FormData object and avoid setting Content-Type header (let the browser set it automatically).

无效尝试

常见但无效的做法:

  1. 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.

  2. 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.

  3. 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.