我已经使用 prisma 成功将我的应用程序连接到 postgres 数据库(我已经设置了一个 seeds.ts 文件,推送它并将数据发送到数据库)。
我遇到的问题是使用我的 api 文件夹中的 Route.js 创建 api 端点。
我正在尝试获取一份注册表单以将数据提交到 postgres 数据库 - 但我不断收到此错误(花了几个小时在论坛中搜索答案),我不确定为什么。
在控制台中,每次提交表单后我都会收到此信息
无法加载资源:服务器响应状态为 405(方法不允许)
这是route.js文件
import prisma from "../../lib/prisma";
export default async function handler(req, res) {
const { name, password, email } = req.query;
try {
const newUer = await prisma.User.create({
data: {
name,
email,
password
},
});
res.json({ user: newUer, error: null });
} catch (error) {
res.json({ error: error.message, user: null });
}
}
表格代码
"use client";
import { useForm } from "react-hook-form";
import { useRouter } from "next/navigation";
import Link from "next/link";
export default function SignUp() {
const { register, reset, formState: { errors }, handleSubmit } = useForm();
const router = useRouter();
const onSubmit = async data => {
console.log(data);
const user = await fetch("api/admin", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
/*if (Object.keys(errors).length === 0) {
router.push("/login");
}
reset();
*/
}
return (
<div>
<h1 className="signUp">Sign up</h1>
<form onSubmit={handleSubmit(onSubmit)} className="signUpForm">
<input
{...register("name", { required: true })} id="first" placeholder="Name"
aria-invalid={errors.name ? "true" : "false"}
/>
{errors.name?.type === 'required' && <p className="errorMessageOne" role="alert">First name is required</p>}
<input {...register("mail", { required: true })} type="mail" id="email" placeholder="Email Address"
aria-invalid={errors.mail ? "true" : "false"} />
{errors.mail && <p className="errorMessage" role="alert">Please enter a valid email address</p>}
<input {...register("password", { required: true, minLength: 4 })} id="password" placeholder="Password must contain a minimum of 8 characters"
aria-invalid={errors.password ? "true" : "false"} />
{errors.password && <p className="errorMessage" role="alert">Please enter a valid password</p>}
<button type="submit" className="signSubmit">Submit</button>
<p className="alreadyText"> Already have an account? <Link href="/login"><span>Login</span></Link></p>
</form>
</div>
);
}
根据官方网站。 要在 API 路由中处理不同的HTTP 方法,您可以在请求处理程序中使用 req.method,如下所示:
import { NextApiRequest, NextApiResponse } from "next";
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method == 'POST') {
console.log(req.body);
return res.status(200).json({ message: 'Method allowed.' });
}
else {
return res.status(405).json({ message: 'Method not allowed.' });
}
}
export default handler;