You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中使用FormData发起Fetch请求失败及TS类型报错问题

NextJS Server Action 请求错误与TS类型问题解决

问题1:FormData 请求返回 400 Bad Request

你在Server Action里给fetch设置了Content-Type: application/json,但直接把FormData作为body传递——这是核心问题。FormData默认的传输格式是multipart/form-data,强制指定json头后,后端会尝试按json解析FormData的内容,自然会抛出Unexpected token - in JSON at position 0的解析错误,导致请求被判定为Bad Request。

解决办法

分两种情况处理,取决于你的后端接口接收格式:

  • 后端接收JSON格式:把FormData转为普通对象后序列化成JSON字符串,保留Content-Type: application/json头
    import { revalidatePath } from "next/cache";
    
    export async function submitIPCR(prevState: any, formData: FormData) {
      try {
        const formDataObj = Object.fromEntries(formData);
        const res = await fetch("http://localhost:8000/ipcr", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: 'same-origin',
          body: JSON.stringify(formDataObj)
        });
    
        if (!res.ok) throw new Error('Something wrong')
        await res.json()
        revalidatePath('/ipcr/new');
        return { message: 'Successfully' }
      } catch (error) {
        console.log(error)
        return { message: 'Error' }
      }
    }
    
  • 后端接收FormData格式:直接移除Content-Type头,浏览器会自动添加正确的multipart/form-data头
    const res = await fetch("http://localhost:8000/ipcr", {
      method: "POST",
      credentials: 'same-origin',
      body: formData
    });
    

问题2:直接传对象给fetch body 触发TS重载错误

fetch的body参数不支持直接传入普通JS对象,它只接受ReadableStream | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | string这些类型。你直接传{ ratee: '' }属于未被允许的类型,所以TypeScript抛出重载匹配错误。

解决办法

把对象序列化成JSON字符串,同时保留Content-Type: application/json头:

const res = await fetch("http://localhost:8000/ipcr", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  credentials: 'same-origin',
  body: JSON.stringify({ ratee: '' })
});

内容的提问来源于stack exchange,提问作者aRtoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 15:07:05