我在 nextjs.13 中获取
/api/user
时遇到问题
// @/app/page.tsx
"use client";
import { FormEvent } from "react";
export default function Home() {
async function handlePost(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
let formData = new FormData(event.currentTarget);
try {
const response = await fetch("/api/user", {
method: "POST",
body: formData,
});
const data = await response.json();
} catch (error) {
console.log(error);
}
}
return (
<form
onSubmit={handlePost}
className="flex flex-col gap-5 w-[300px] m-auto mt-[200px]"
>
<input type="text" name="name" id="name" />
<input type="email" name="email" id="email" />
<input type="password" name="password" id="password" />
<button type="submit">Submit</button>
</form>
);
}
// @/app/api/user/route.ts
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
interface PostRequest {
body: {
name: string;
email: string;
password: string;
};
}
export async function POST(request: PostRequest) {
await prisma.user.create({
data: {
name: request.body.name,
email: request.body.email,
password: request.body.password,
},
});
console.log(request.body);
return prisma.user.findFirst();
}
这就是出现的错误
Argument `name` is missing.
at xn (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:116:5852)
at vn.handleRequestError (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:123:6429)
at vn.handleAndLogRequestError (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:123:6119)
at vn.request (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:123:5839)
at async l (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:128:9763)
at async POST (webpack-internal:///(rsc)/./src/app/api/user/route.ts:10:5)
at async eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:37) {
clientVersion: '5.2.0'
}
此外,当我安慰
formData
时,它记录了未定义
我尝试用
替换
formData
body: JSON.stringfy({
name: "myname",
email: "[email protected]",
password: "my password"
});
但是,错误发生了
接下来的13,要访问request.body,可以使用await request.json()。我在 GitHub 上的一次讨论中找到了这个答案:https://github.com/vercel/next.js/discussions/46483。我希望这有帮助。 这是如果在您的代码中实现的话。
import { PrismaClient } from "@prisma/client";
import { NextRequest } from "next/server";
const prisma = new PrismaClient();
export async function POST(request: NextRequest) {
const body = await request.json();
await prisma.user.create({
data: {
name: body.name,
email: body.email,
password: body.password,
},
});
console.log(body);
return prisma.user.findFirst();
}