Home > Back-end >  TypeError: res.json is not a function (not able to get fetch data)
TypeError: res.json is not a function (not able to get fetch data)

Time:11-23

I m trying to GET response using fetch API not stuck in a error as I mentioned below. Here's my code

const DefaultLayout = () => {
      let history = useHistory()
      const callHomePage = async () => {
        try {
          const res = fetch('http://localhost:4000/api/authenticate', {
            method: 'GET',
            headers: {
              Accept: 'application/json',
              'Content-type': 'application/json',
            },
            credentials: 'include',
          })
          console.log(res)
          const data = await res.json()
          console.log(data)
          if (!res.status === 200) {
            const error = new Error(res.error)
            throw error
          }
        } catch (err) {
          console.log(err)
          history.push('login')
        }
    }

Error: TypeError: res.json is not a function Promise {} shows pending

CodePudding user response:

const DefaultLayout = () => {
  let history = useHistory()
  const callHomePage = async () => {
    try {
      const res = await fetch('http://localhost:4000/api/authenticate', {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-type': 'application/json',
        },
        credentials: 'include',
      })
      console.log(res)
      const data = await res.json()
      console.log(data)
      if (!res.status === 200) {
        const error = new Error(res.error)
        throw error
      }
    } catch (err) {
      console.log(err)
      history.push('login')
    }
}

CodePudding user response:

You need to await the fetch statement and then call the .json method of the response.

const res = await fetch(...)

data = res.json();

Read more: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

  • Related