Home > Mobile >  React & Sanity - Fetch Error: invalid JSON response body
React & Sanity - Fetch Error: invalid JSON response body

Time:06-03

I have been following a tutorial on youtube to build a twitter-clone website. However, when trying to fetch tweets from Sanity I am getting this error. I even git cloned the repo of the person that made the tutorial and I'm still getting the same error. This leads me to believe it is an issue with my VS code and not the code itself, if anyone has any suggestions that would be great thank you.

// fetchTweets.ts

export const fetchTweets = async () => {
  const res = await fetch(`http://localhost:3001/api/getTweets`)

  const data = await res?.json()
  const tweets: Tweet[] = data.tweets

  console.log('fetching', tweets)

  return tweets
}
// index.tsx

export const getServerSideProps: GetServerSideProps = async (context) => {
  const tweets: Tweet[] = await fetchTweets()

  return {
    props: {
      tweets,
    },
  }
}

screenshot of fetch error in browser

CodePudding user response:

That error is typically caused by trying to render HTML as JSON—and particularly, when JSON is expected but instead an API returns an error page. Is your server definitely running on port 3001? Fetching from a non-existent server is likely consistent with this error.

  • Related