0

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

Gugu72
  • 2,052
  • 13
  • 35
Caro
  • 1
  • 1
  • how about you try putting some console.logs after each of the statements to see where it's getting stuck. Also you should use a try catch block when doing requests like these so that way if any one of these statements ever fail it can throw an error by default. It's good practice. – Nikster Aug 25 '23 at 18:04
  • I finally found the problem yesterday, it was because of the folder name for my fbackend file, i forgot to use [id] . now i have an 404 error so that's a progress. Thank you for your answer – Caro Aug 26 '23 at 06:53
  • any progress on your error? – Nikster Aug 30 '23 at 00:31

0 Answers0