Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON , graphQLClient Error

807 views Asked by At

I am making a blog website and using graphcms backend with GraphQl, I made a comment form and trying to get data from client side , i am using next js build in api folder to make an endpoint to createcomment , But i am getting error when someone clicks the submit button "Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON" does any one know how to fix this error?

pages/Api/comments.js

import { GraphQLClient , gql } from "graphql-request";

export default async function comments(req, res) {

  const graphQLClient = new GraphQLClient(process.env.NEXT_PUBLIC_GRAPHCMS_ENDPOINT, {
    headers: {
      Authorization: `Bearer ${process.env.GRAPHCMS_TOKEN}`,
    },
  }
  );

  const query = gql`
  mutation MyMutation {
    createComment(data: {name: "", email: "", comment: ""}) {
      comment
      email
      name
    }
  }
  `;
  
  const result = await graphQLClient.request(query,req.body);
  
try {
  return res.status(200).send(result)
} catch (error) {
  return res.status(500).send(error)
}

}

services/index.js

export const submitComment = async (obj) => {
  const result = await fetch('/api/comments', {
    method:'POST',
    headers:{
      'Content-Type':'application/json'
    },
    body:JSON.stringify(obj)
  })
  return result.json()
};

Components/commentsForm.js

const handleCommentsSubmission = () =>{
    setError(false);

    const{value:comment} = commentEl.current;
    const{value:name} = nameEl.current;
    const{value:email} = emailEl.current;
    const{checked:storeData} = storeDataEl.current;

    if(!comment || !name || !email) {
      setError(true);
      return;
    }

    const commentObj = {
      name ,email , comment
    };
    
    if(storeData){
      window.localStorage.setItem('name',  name)
      window.localStorage.setItem('email',  email)
    }else{
      window.localStorage.removeItem('name',name);
      window.localStorage.removeItem('email',email);

    }
    submitComment(commentObj)
    .then((res)=>{
      setShowSuccessMessage(true);
      setTimeout(() => {
        setShowSuccessMessage(false)
      }, 3000);
    })
  }

I tried everything but nothing seems to work :(

0

There are 0 answers