Sending POST request to a Next.js API route sending a 500 Internal Server Error

Viewed 57

Here is the code for createComment.ts file which is a Next.js api route

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


const config = {
  dataset: process.env.NEXT_PUBLIC_SANITY_DATSET,
  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 (error) {
    return res.status(500).json({message: "Couldn't submit comment", error})
  }


  console.log("Comment submitted")
  res.status(200).json({ message: 'Comment Submitted Successfully' })
}

And here is my frontend code which is being used to send a POST request to the api route via Fetch API

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

I am getting this error even after clearing my cache and restarting the server several times, but no luck.

0 Answers
Related