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

NextJS14+Supabase问题:客户端FormData正常,服务端接收为空

问题原因及解决方案

核心问题

你的自定义MyInput组件里的<input>标签没有设置name属性。FormData是通过表单元素的name属性来收集数据的,缺少这个属性时,new FormData(event.currentTarget)无法从表单中提取任何字段,导致服务端收到空的FormData对象。

虽然你在前端通过state维护了formData并能正常打印,但这和FormData的自动收集逻辑完全独立。

修复步骤

1. 给MyInput组件的input添加name属性

修改MyInput组件的返回部分,给<input>加上name={name}:

return (
  <div className="mb-4">
    <label className="block text-lg font-semibold text-blue-700 mb-2">{label}</label>
    <input
      type={type}
      name={name} {/* 新增这一行 */}
      value={value}
      onChange={handleInputChange}
      onBlur={validateInput}
      placeholder={placeholder}
    />
    {error && <p className="text-red-500 text-lg italic mt-2">{error}</p>}
  </div>
);

2. 可选:直接传递前端state给服务端Action

如果你不想依赖FormData自动收集,也可以直接把前端维护的formData对象传给服务端Action,更贴合当前的状态管理逻辑:

修改表单组件的onSubmit函数

async function onSubmit(event: FormEvent<HTMLFormElement>) {
  event.preventDefault();

  console.log(formData,"formData under waterStation file form");
  // 直接传递formData,而非创建新的FormData
  const res = await addWaterStation(formData);
  setMessage(res.message);
}

修改服务端Action的参数类型

由于现在传递的是普通对象而非FormData,需要调整服务端Action的参数:

'use server'

import { createServerComponentClient } from "@supabase/auth-helpers-nextjs"
import { revalidatePath } from "next/cache";
import { cookies } from "next/headers"

// 定义与前端一致的表单数据类型
interface FormData {
  name: string;
  landmark: string;
  buildingNumber: string;
  street: string;
  zone: string;
  // 其他字段
}

export default async function addWaterStation(formData: FormData): Promise<{ message: string }> {
  console.log(formData, "form data under water station.ts");
  const supabase = createServerComponentClient({cookies});
  const {data: {user}} = await supabase.auth.getUser();
  const formDataAddress = `${formData.buildingNumber}, ${formData.street}, ${formData.zone}`;

  try{
      const station_name = formData.name;
      // 其他字段直接从formData对象获取
      
      const {data, error} = await supabase.from('water_refilling_station')
          .insert({
              station_name,
              // 其他字段
          }).select();
      
      if(error){
          return {message: `${error.message}  - unable to save`};
      } 

      revalidatePath('/n');
      return{message: 'Succesfully Added the Water Station Information'};
  }catch(e){
      return {message: "Failed to submit the form."};
  }
}

验证

修复后,无论使用FormData自动收集还是直接传递state,服务端都能正常接收表单数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:58:10