Next.js中无法通过表单更新Prisma数据库用户信息求助
问题分析与解决方案
核心问题
从错误信息和代码来看,主要有3个关键问题:
- 前端未正确发起API请求,且未传递有效参数到后端
- 前端未获取当前登录用户的邮箱,导致后端
where条件缺少唯一标识 - 后端未做参数校验,当参数为空时触发Prisma的无效调用错误
前端代码修复(step2.js)
1. 引入NextAuth的用户会话获取用户邮箱
因为是NextAuth谷歌登录,需要用useSession钩子获取当前用户的邮箱,作为更新的唯一标识。
2. 正确使用useForm的register,避免手动维护state
3. 修复fetch请求的写法,正确传递请求体
修改后的step2.js代码:
import { useForm } from "react-hook-form"; import { useSession } from "next-auth/react"; import { toast } from "react-toastify"; const Step2 = () => { const { handleSubmit, register } = useForm(); const { data: session } = useSession(); // 获取当前登录用户会话 const updateUserInfo = async (data) => { if (!session?.user?.email) { throw new Error("用户未登录"); } try { const response = await fetch("http://localhost:3000/api/update", { body: JSON.stringify({ email: session.user.email, orgName: data.orgName }), headers: { "Content-Type": "application/json", }, method: "PUT", }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.message || "更新失败"); } return await response.json(); } catch (error) { throw error; // 抛出错误让toast捕获 } }; const onSubmit = async (data) => { try { await toast.promise( updateUserInfo(data), { loading: "正在更新...", success: "更新成功!", error: "更新失败,请稍后重试" }, { duration: 3000, } ); } catch (error) { toast.error(error.message); } }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input type="text" name="orgName" placeholder="Spacely Sprockets LLC" className="inputAreaFull" {...register("orgName", { required: true })} // 使用useForm的register /> <button className="generalButton" type="submit"> Continue </button> </form> ); }; export default Step2;
后端代码修复(update.js)
1. 添加参数校验,确保email和orgName存在后再执行更新
2. 处理Prisma可能的异常(比如用户不存在的情况)
修改后的update.js代码:
import { PrismaClient } from "@prisma/client"; export default async function handler(req, res) { if (req.method !== "PUT") { return res.status(405).json({ message: "仅支持PUT请求" }); } const prisma = new PrismaClient(); const { email, orgName } = req.body; // 参数校验 if (!email || !orgName) { return res.status(400).json({ message: "缺少必要参数:email和orgName不能为空" }); } try { const updatedUser = await prisma.user.update({ where: { email: email }, data: { orgName: orgName }, }); res.status(200).json(updatedUser); } catch (error) { // 处理用户不存在的情况 if (error.code === "P2025") { return res.status(404).json({ message: "用户不存在" }); } res.status(400).json({ message: `更新失败:${error.message}` }); } finally { await prisma.$disconnect(); // 断开Prisma连接,避免资源泄漏 } }
测试验证
- 确保用户已通过谷歌登录到应用
- 在表单中输入orgName并提交,此时会正确传递用户邮箱和orgName到后端
- 查看Prisma Studio,确认orgName字段已更新
- 用Postman测试时,需要在请求体中传入
email和orgName的JSON数据:
{ "email": "somename.co@gmail.com", "orgName": "新的公司名称" }
内容的提问来源于stack exchange,提问作者Noble Polygon
相关产品推荐
相关产品推荐

