由于错误 500,无法使用 next 和 prisma 在 React 上提交表单

问题描述 投票:0回答:1

我有一个表格,应该发送对博客文章的评论,我收到错误 500,我不明白为什么。

我尝试更改我拨打的路线,但我不确定它来自那里。 也许我应该在其他地方提到 postId 吗?我真的很困惑。

这里是对后面的调用:

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

    const body = {
      authorEmail,
      content,
    };

    try {
      const response = await fetch(`/api/comment?id=${postId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body),
      });

      if (response.ok) {
        const createdComment = await response.json();
        console.log('Comment created:', createdComment);
      } else {
        const errorData = await response.json();
        console.error('Error creating comment:', errorData);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  }

这里是背面:

export const createComment = async (
    { body, query }: NextApiRequest,
    res: NextApiResponse,
) => {
    // Verificate the params
    if (!query.id) return res.status(400).json({ error: 'Missing id' })
    if (!body.authorEmail || !body.content) return res.status(400).json({ error: 'Missing fields' })

    // Convert the id to an integar
    const postId = +query.id

    // search the article with the post id
    const verifiedId = await prisma.post.findUnique({
        where: { id: postId },
    })
    if (!verifiedId) return res.status(400).json({ error: 'Post not found' })

    //fetch the datas comment from the request body
    const { authorEmail, content }: { authorEmail: string, content: string } = body

    //search the author
    const author = await prisma.user.findUnique({
        where: { email: authorEmail },
    })
    if (!author) return res.status(400).json({ error: 'Author not found' })

    // Create the comment in the db
    const comment = await prisma.comment.create({
        data: {
            userId: author.id,
            postId,
            content,
        },
    })

    return res.status(200).json(comment)
}

可能很简单

我尝试改变路线 我添加了 postId 的类型

reactjs next.js prisma http-status-code-500 next-api
1个回答
0
投票

API路径不正确。在您的评论中,您提到您正在使用 [id]/route,而您显然是在通话中的查询中发送 ID。这会导致 404 错误,因为没有像

api/comment/123
这样的动态页面。

对于给定的上下文,我建议将后端代码放在

api/comment/route.ts
文件中。

© www.soinside.com 2019 - 2024. All rights reserved.