Kl-Rahul's avatar

FetchError: invalid json response body reason: Unexpected token < in JSON at position 0

Error FetchError: invalid json response body at https://matdevsolution.com/ reason: Unexpected token < in JSON at position 0

Screenshot:: https://prnt.sc/4Ytg4sZZkHCB

URL:: http://localhost:3000/api/page/home

My Code

export default async (req, res) => {
    const { query: { slug } } = req;
    ///const uri = slug;
    const QUERY_SINGLE_PAGE = `
       query getPage($id: ID!) {
           page(id: $id, idType: URI) {
               title
              content
        }
    }
`;

const data = await fetch( process.env.NEXT_PUBLIC_WORDPRESS_API_URL, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ 
    query: QUERY_SINGLE_PAGE,
    variables: {
      id: slug
      }
    })
  } );

   const json = await data.json();
   res.json(json) ;
 }
0 likes
13 replies
Sinnbeck's avatar

Check the browser network tab to see what is returned. By guess is that it isnt valid json (html perhaps?)

Sinnbeck's avatar

@Kl-Rahul That is your js file. Click on the Fetch/HXR tab and make the request that fails. It should show up then. Then click it and select the Preview tab

Sinnbeck's avatar

@Kl-Rahul I have never used next myself, but I use react (and general js). And according to the error it seems that there should be a request, but the returned data is invalid

1 like
Kl-Rahul's avatar

@Sinnbeck So any idea how to solve this, Plaese help if possible your end, i am stuck since 3 days on this error

Sinnbeck's avatar

@Kl-Rahul So when you click the button (or whatever triggers that code), you dont get a new line in the networks tab ?

Sinnbeck's avatar

@Kl-Rahul Great. That is the problem. You are expecting json. So fix whatever code is returning that failed html (show the code for the endpoint if you need help)

Kl-Rahul's avatar

@Sinnbeck Folder \lib

import { ApolloClient, InMemoryCache } from "@apollo/client";
export const client = new ApolloClient({
   uri: `${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/graphql`,
   cache: new InMemoryCache(),
});

.env file

  NEXT_PUBLIC_WORDPRESS_API_URL=https://matdevsolution.com
Sinnbeck's avatar

@Kl-Rahul That is your endpoint? /api/page/home

This isnt a laravel project at all?

Sinnbeck's avatar

@Kl-Rahul I dont really use wordpress either. So you need to figure out why that endpoint is returning html instead of json and fix that

1 like

Please or to participate in this conversation.