'Why am I getting Unexpected end of JSON input in my createComment API function in Next.js app?

When I try to post a comment on my blog to Sanity database nothing shows up. And when I go to the /api/createComment route this pulls up in the browser:

enter image description here

Here's the code for createComment endpoint:

 import type { NextApiRequest, NextApiResponse } from 'next'
  import   sanityClient   from '@sanity/client'

  const config = {
    dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
    projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
    useCdn: process.env.NODE_ENV === "production",
    token: process.env.SANITY_API_TOKEN,
   };

  const client = sanityClient(config);



  export default async function createComment(
     req: NextApiRequest,
     res: NextApiResponse
  ) {
        const { _id, name, email, comment } = req.body;


        try {
            await client.create({
                 _type: comment,
                 post: {
                 _type: 'reference',
                 _ref: _id
                },
                 name,
                 email,
                 comment
                });
           } catch(err) {
           return res.status(500).json({ message: 'Couldnt submit 
        comment', err});
       }
    console.log(req.body);
    console.log('Comment submitted');  
    res.status(200).json({ message: 'Comment submitted' });
  }



 

So I console.log(req.body) inside the api function and everything appears just fine in the browser like so:

enter image description here

This is what the submit handler looks like in the page.tsx:

 const onSubmit: SubmitHandler<IFormInput> = async (data) => {
  await fetch('/api/createComment', {
      method: 'POST',
      body: JSON.stringify(data)
  }).then(() => {
      console.log(data);
  }).catch((err) => {
      console.log(err);
  })

So if req.body is populating in the browser console then why am I getting an Unexpected end of JSON input? Wouldn't that imply that req.body is not populated with anything?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source