nextjs protocol_error ai_generated true

错误:服务器操作需要将请求体解析为 FormData 或 JSON。收到意外的内容类型。

Error: Server Actions require the request body to be parsed as FormData or JSON. Received unexpected content type.

ID: nextjs/server-action-body-parsed-json-error

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

版本兼容性

版本状态引入弃用备注
14.2.0 active
14.2.1 active
15.0.0 active
15.1.0 active

根因分析

Next.js 中的服务器操作期望客户端发送带有 Content-Type application/x-www-form-urlencoded 或 multipart/form-data(用于表单提交)或 application/json(用于编程调用)的请求。不支持的内容类型(例如 text/plain)会导致解析失败。

English

Server Actions in Next.js expect the client to send requests with Content-Type application/x-www-form-urlencoded or multipart/form-data (for form submissions) or application/json (for programmatic calls). An unsupported content type (e.g., text/plain) causes parsing failure.

generic

官方文档

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

解决方案

  1. Ensure client-side form submissions use the standard HTML form element or the 'useFormState' hook, which automatically sends the correct content type. For programmatic calls, use 'new FormData(formElement)' or pass a plain object and set Content-Type: application/json.
  2. If using fetch directly, construct the body as FormData: const formData = new FormData(); formData.append('key', value); await fetch('/action', { method: 'POST', body: formData });

无效尝试

常见但无效的做法:

  1. Adding 'Content-Type: multipart/form-data' header manually in JavaScript fetch calls without properly encoding the body 70% 失败

    The server still receives the body as a string, not as multipart parts. The content type must match the actual encoding.

  2. Setting 'bodyParser: false' in API route configuration for Server Actions 90% 失败

    Server Actions do not use the API route body parser; they have their own parsing logic. Disabling it has no effect.

  3. Using JSON.stringify on FormData before sending 95% 失败

    FormData is not a plain object; JSON.stringify will return an empty object. The server expects actual FormData entries.