Can't submit a form on react using next and prisma because of an error 500

67 Views Asked by At

I have a form that is suppose to sent comment on a blog article, i receive an error 500 and i don't understand why.

I tried to change the route that i call but i'm not sure it comes from that. Maybe shoul i mentionned somewhere else the postId? i'm really confused.

here is the call to the back:

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);
    }
  }

And here the back:

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)
}

it's probably simple

I tried to change the route on the try I add the type for postId

1

There are 1 best solutions below

0
Abdul Rehman On

The API route is not correct. In your comment you mentioned that you are using [id]/route whereas you are clearly sending ID in query in your call. This is causing 404 error because there is no route in backend like api/comment.

For the given context I would recommend to place your backend code in api/comment/route.ts file.