51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

错误 500 在请求 POST 时出现 – Next JS 13 应用程序目录

英文:

Error 500 when request POST - Next JS 13 app directory

问题 {#heading}

我创建了一个简单的路由来创建用户。
当我发送请求时,我收到错误消息:500 Internal Server Error

日志显示:

错误 TypeError:res.status 不是一个函数
    在 POST (webpack-internal:///(rsc)/./app/api/register/route.ts:33:20)
    在异步评估 (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:37)

我的路由位于 app/api/register/route.ts 中,
而我的组件在 app/components/Connextion.tsx 中调用了该路由。

以下是我的组件:

function Connexion() {
    const [hasAccount, setHasAccount] = useState<boolean>(true);
    const [email, setEmail] = useState<string | null>(null);
    const [password, setPassword] = useState<string | null>(null);
    const [confirmPassword, setConfirmPassword] = useState<string | null>(null);

    const register = useCallback(async () => {
        try {
            if (password !== confirmPassword) Notifier("密码不匹配", "error");

            await axios.post("/api/register", {
                email,
                password,
            });
        } catch (error) {
            console.error(error);
        }
    }, [email, password, confirmPassword]);

    return (
[...]

这是我的路由:

import bcrypt from "bcrypt";
import { NextApiRequest, NextApiResponse } from "next";
import prismadb from "@/lib/prismadb";

export async function POST(req: NextApiRequest, res: NextApiResponse) {
    try {
        if (req.method !== "POST") return res.status(405).end();
        const { email, password } = req.body;

        const existingUser = await prismadb.user.findUnique({
            where: {
                email,
            },
        });

        if (existingUser) return res.status(422).json({ error: "电子邮件已存在。请登录。" });

        const hashedPassword = await bcrypt.hash(password, 12);

        const user = await prismadb.user.create({
            data: {
                email,
                hashedPassword,
                image: "",
                emailVerified: new Date(),
            },
        });

        return res.status(200).json(user);
    } catch (error) {
        return res.status(400).json({ error: `出现错误:${error}` });
    }
};

在POSTMAN上发送的请求返回相同的错误。

我犯了什么错误?非常感谢! 英文:

I creating a simple route to create a user.
When I send the request I get error : 500 Internal Server Error.

The logs shows :

 error TypeError: res.status is not a function
    at POST (webpack-internal:///(rsc)/./app/api/register/route.ts:33:20)
    at async eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:37)

I have my route in app/api/register/route.ts
And my component calling the route in app/components/Connextion.tsx

Here is my component :

function Connexion() {
    const [hasAccount, setHasAccount] = useState&lt;boolean&gt;(true);
    const [email, setEmail] = useState&lt;string | null&gt;(null);
    const [password, setPassword] = useState&lt;string | null&gt;(null);
    const [confirmPassword, setConfirmPassword] = useState&lt;string | null&gt;(null);

    const register = useCallback(async () =&amp;gt; {
        try {
            if (password !== confirmPassword) Notifier(&amp;quot;Passwords do not match&amp;quot;, &amp;quot;error&amp;quot;);

            await axios.post(&amp;quot;/api/register&amp;quot;, {
                email,
                password,
            });
        } catch (error) {
            console.error(error);
        }
    }, [email, password, confirmPassword]);

    return (



`[...]
`

And my route :

import bcrypt from &quot;bcrypt&quot;;
import { NextApiRequest, NextApiResponse } from &quot;next&quot;;
import prismadb from &quot;@/lib/prismadb&quot;;

export async function POST(req: NextApiRequest, res: NextApiResponse) {
try {
if (req.method !== \&quot;POST\&quot;) return res.status(405).end();
const { email, password } = req.body;


        const existingUser = await prismadb.user.findUnique({
            where: {
                email,
            },
        });

        if (existingUser) return res.status(422).json({ error: &amp;quot;E-mail already exists. Login instead.&amp;quot; });

        const hashedPassword = await bcrypt.hash(password, 12);

        const user = await prismadb.user.create({
            data: {
                email,
                hashedPassword,
                image: &amp;quot;&amp;quot;,
                emailVerified: new Date(),
            },
        });

        return res.status(200).json(user);
    } catch (error) {
        return res.status(400).json({ error: `Something went wrong: ${error}` });
    }



`};
`

The request on POSTMAN returns the same error.

Where is my mistake ? Thank you very much

答案1 {#1}

得分: 1

在下面的13行代码中,你可以在路由处理程序中使用 NextResponse:

import { NextResponse } from 'next/server'
 
export async function GET(req: NextApiRequest) {
  // 这里是你的逻辑
          const user = await prismadb.user.create({
            data: {
                email,
                hashedPassword,
                image: "",
                emailVerified: new Date(),
            },
        });
 
  return NextResponse.json({ user }, {status: 200})
}

英文:

In next 13 you can use NextResponse in route handlers:

import { NextResponse } from &#39;next/server&#39;
 
export async function GET(req: NextApiRequest) {
  // Here your logic
          const user = await prismadb.user.create({
            data: {
                email,
                hashedPassword,
                image: &quot;&quot;,
                emailVerified: new Date(),
            },
        });
 
  return NextResponse.json({ user }, {status: 200})
}

赞(1)
未经允许不得转载:工具盒子 » 错误 500 在请求 POST 时出现 – Next JS 13 应用程序目录