简体   繁体   English

TypeError: res.json is not a function(无法获取数据)

[英]TypeError: res.json is not a function (not able to get fetch data)

I m trying to GET response using fetch API not stuck in a error as I mentioned below.我正在尝试使用 fetch API 获取响应,而不是陷入错误,如下所述。 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错误: TypeError: res.json is not a function Promise {}显示待处理

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')
    }
}

You need to await the fetch statement and then call the .json method of the response.您需要await fetch 语句,然后调用响应的.json方法。

const res = await fetch(...)

data = res.json();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM