1

I am trying to figure out where to look for an error in my app that is reported in my browser console as follows:

Error: Unexpected token '<', "<!doctype "... is not valid JSON
    at new ApolloError (index.js?6610:29:1)
    at Object.error (QueryManager.js?7fcd:137:74)
    at notifySubscription (module.js?580a:137:1)
    at onNotify (module.js?580a:176:1)
    at SubscriptionObserver.error (module.js?580a:229:1)
    at Object.eval [as error] (asyncMap.js?b322:32:41)
    at notifySubscription (module.js?580a:137:1)
    at onNotify (module.js?580a:176:1)
    at SubscriptionObserver.error (module.js?580a:229:1)
    at eval (iteration.js?8d45:4:50)
    at Array.forEach (<anonymous>)
    at iterateObserversSafely (iteration.js?8d45:4:1)
    at Object.error (Concast.js?a4f8:36:43)
    at notifySubscription (module.js?580a:137:1)
    at onNotify (module.js?580a:176:1)
    at SubscriptionObserver.error (module.js?580a:229:1)
    at RetryableOperation.eval (retryLink.js?c650:55:1)
    at step (tslib.es6.js?f7a0:102:1)
    at Object.eval [as next] (tslib.es6.js?f7a0:83:46)
    at fulfilled (tslib.es6.js?f7a0:73:43)

It's a next app, so I think I'm supposed to construe the reference to index.js as a reference to _app.tsx.

I can't see a stray < in that file.

import * as React from "react"
// import { BrowserRouter } from "react-router-dom"
import { ApolloProvider } from "@apollo/client"
import { theme } from "@boilerplate/theme"
import { ChakraProvider } from "@chakra-ui/react"
import type { NextPage } from "next"
import type { AppProps } from "next/app"
import Head from "next/head"
import Script from "next/script"
// import { useRef } from 'react';

// import TawkMessengerReact from '@tawk.to/tawk-messenger-react';


import { useApollo } from "lib/apollo/client"

type NextPageWithLayout = NextPage & {
  getLayout?: (page: React.ReactElement) => React.ReactNode
}

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}

export default function BoilerplateApp(props: AppPropsWithLayout) {
  const { Component, pageProps } = props
  const apolloClient = useApollo(pageProps.initialApolloState)
  const getLayout = Component.getLayout ?? ((page) => page)
  
  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </Head>
      {/* <BrowserRouter> */}
      <ChakraProvider theme={theme}>
        <ApolloProvider client={apolloClient}>{getLayout(<Component {...pageProps} />)}</ApolloProvider>
      </ChakraProvider>
      {/* </BrowserRouter> */}
      {/* <Button onClick={handleMinimize}> Minimize the Chat </Button> */}

      <Script id="tawk" strategy="lazyOnload">
        {`
            var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
            (function(){
            var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
            s1.async=true;
            s1.src='https://embed.tawk.to/xx/xx';
            s1.charset='UTF-8';
            s1.setAttribute('crossorigin','*');
            s0.parentNode.insertBefore(s1,s0);
            })();  
        `}
      </Script>
     
      

      
    </>
  )
}

I'm not getting any errors in my VS Code terminal.

Can anyone help with a clue for how to find the error? When I run local host, the page loads, but when I fill in a form to make a user in my psql db, I get no response - just no user created.

I have found this article, but still can't see what I'm supposed to be looking for.

In the sources tab of my chrome browser, I can see the register page is identified (possibly as the source of the problem). That page has something that starts with doctype (and goes on with lots of random strings):

<!DOCTYPE html><html lang="en"><head><style data-next-hide-fouc="true">body{display:none}</style><noscript data-next-hide-fouc="true"><style>body{display:block}</style></noscript><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="next-head-count" content="2"/><meta name="theme-color" content="#000000"/><meta name="description" content="test"/><meta property="og:title" content="testing"/><meta property="og:description" content="test"/><link rel="preconnect" href="https://fonts.gstatic.com"/><link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700;1,800&amp;display=swap" rel="stylesheet"/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills.js?ts=1663664583953"></script><script src="/_next/static/chunks/webpack.js?ts=1663664583953" defer=""></script><script src="/_next/static/chunks/main.js?ts=1663664583953" defer=""></script><script src="/_next/static/chunks/pages/_app.js?ts=1663664583953" defer=""></script><script src="/_next/static/chunks/pages/register.js?ts=1663664583953" defer=""></script><script src="/_next/static/development/_buildManifest.js?ts=1663664583953" defer=""></script><script src="/_next/static/development/_ssgManifest.js?ts=1663664583953" defer=""></script><script src="/_next/static/development/_middlewareManifest.js?ts=1663664583953" defer=""></script><noscript id="__next_css__DO_NOT_USE__"></noscript></head><body><script>(function setScript(initialValue) {
  var mql = window.matchMedia("(prefers-color-scheme: dark)");
  var systemPreference = mql.matches ? "dark" : "light";
  var persistedPreference = systemPreference;

  try {
    persistedPreference = localStorage.getItem("chakra-ui-color-mode");
  } catch (error) {
    console.log("Chakra UI: localStorage is not available. Color mode persistence might not work as expected");
  }

  var colorMode;

  if (persistedPreference) {
    colorMode = persistedPreference;
  } else if (initialValue === "system") {
    colorMode = systemPreference;
  } else {
    colorMode = initialValue != null ? initialValue : systemPreference;
  }

  if (colorMode) {
    /**
     * Keep in sync with `root.set() {@file ./color-mode.utils.ts}
     */
    document.documentElement.style.setProperty("--chakra-ui-color-mode", colorMode);
    document.documentElement.setAttribute("data-theme", colorMode);
  }

.... it continues on with lots of random chakra things before ending as follows:

</path></svg></a></div></div></div></div></div><span></span></div><script src="/_next/static/chunks/react-refresh.js?ts=1663664583953"></script><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{}},"page":"/register","query":{},"buildId":"development","nextExport":true,"autoExport":true,"isFallback":false,"scriptLoader":[]}</script></body></html>

In VS code, the register form does have JSON in it - in the submit handler, it has:

    const onSubmit = (data: RegisterInput) => {
        return form.handler(() => register({ variables: { data } }), {
          onSuccess: async (data) => {
            await fetch("/api/login", {
              method: "post",
              body: JSON.stringify({
                [LOGIN_TOKEN_KEY]: data.register.token,
                [LOGIN_REFRESH_TOKEN_KEY]: data.register.refreshToken,
              }),
            })
            client.writeQuery<MeQuery>({ query: MeDocument, data: { me: data.register.user } })
            router.replace(redirect || "/")
          },
        })

I think the advice from the stripe article linked above means I'm supposed to move that into a try block. When I try that, I get an error that says:

 const onSubmit = (data: RegisterInput) => {
    return form.handler(() => register({ variables: { data } }), {
      onSuccess: async (data) => {
        await fetch("/api/login", {
          method: "post",

          body:
         { try {
              JSON.stringify({
              [LOGIN_TOKEN_KEY]: data.register.token,
              [LOGIN_REFRESH_TOKEN_KEY]: data.register.refreshToken,
              }),
          },
          catch (error): void {
            console.log('Error parsing JSON:', error, data);
          }}
        }
         
          
        })
        client.writeQuery<MeQuery>({ query: MeDocument, data: { me: data.register.user } })
        router.replace(redirect || "/")
      },
    })
 

Type '{ try: { JSON: JSON; "": any; }; catch(error: any): void; }' is not assignable to type 'BodyInit | null | undefined'. Object literal may only specify known properties, and 'try' does not exist in type 'Blob | ReadableStream | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams'.

I think I'm not incorporating the try statement correctly in the submit handler, but I don't know how to do that differently - it's all underlined by copilot in the try block - I can't figure a better way to try to write it.

I also tried adding JSON.parse in front of the JSON.stringify block in the submit handler, as follows:

body: JSON.parse(JSON.stringify({
            [LOGIN_TOKEN_KEY]: data.register.token,
            [LOGIN_REFRESH_TOKEN_KEY]: data.register.refreshToken,
          })),

but it doesn't change anything - i still get the same error message in the browser.

I also tried it as follows (but no difference- and github copilot does not like that code - i don't know why)

 body: try {
          JSON.parse(JSON.stringify({
              [LOGIN_TOKEN_KEY]: data.register.token,
              [LOGIN_REFRESH_TOKEN_KEY]: data.register.refreshToken,
           })
           ),
        }, catch (e) {
          console.log('error parsing json', e, data));
        },
        })

I saw this post and have tried each of the approaches suggested in the solutions, on the register form - and still can't find a way to get this resolved.

In the network tab of chrome, all the status types show as 200 (ok), except for a websocket string (i dont know what that string is meant to convey) that is status 101.

Mel
  • 2,481
  • 26
  • 113
  • 273
  • 2
    please have a look at your ajax responses. chances are that one of them is returning a page rather than json. – naveen Sep 17 '22 at 01:43
  • How can I identify what an ajax response is in my code? Is there a statement that I could use to search for what that might be? – Mel Sep 17 '22 at 01:50
  • you could use the network tab in your console and look for the all the xhr responses? – naveen Sep 17 '22 at 01:53
  • Do you know anything else I can try? – Mel Sep 17 '22 at 02:05
  • all your ajax returns are returning json? I guess you are using graphql with the api. I would inspect the call closely. cant say much without the code – naveen Sep 17 '22 at 02:21
  • What does it mean to inspect the call? Sorry - I'm not familiar with the terminology? I am using graphql. I can't find which file I should be trying to search for errors within – Mel Sep 17 '22 at 02:24
  • network tab itself. I dont see anything else. sorry – naveen Sep 17 '22 at 02:43

1 Answers1

2

I don't know why this worked or how it can be construed as a json error, but I ended up deleting my psql and reinstalling it. When I reinstalled it, all of these issues went away. That does not make any sense to me, and I dont understand how a psql address in the env variables could be construed as a json error, but after days of looking for what could be the problem, I am finally moving forward again. I hope this helps someone.

Mel
  • 2,481
  • 26
  • 113
  • 273
  • 2
    Look... The thing here is that your code is kinda too verbose. To not say a mess. You did a fetch request to get Data from the backend. But the Postgres env vars were wrong, then the data couldnt be fetched, the backend returned an error that was translated to a page, and not to the expected data format to be parsed by JSON. – Carlos Sep 26 '22 at 17:38