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
相关产品推荐
相关产品推荐

