nextjs protocol_error ai_generated true

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

Also available as: JSON · Markdown · 中文
92%Fix Rate
88%Confidence
1Evidence
2024-06-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
14.2.0 active
15.0.0 active
14.2.15 active

Root Cause

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

中文

服务器操作以非标准内容类型(例如 application/x-www-form-urlencoded)被调用,而非 multipart/form-data 或 application/json。这通常发生在通过 fetch 手动提交表单而未设置正确标头时。

Official Documentation

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

Workarounds

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

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. Adding 'Content-Type: multipart/form-data' manually without FormData 85% fail

    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% fail

    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% fail

    FormData cannot be serialized with JSON.stringify. You must send the FormData object directly as the body.