【问题标题】:TypeError: res.json is not a function (not able to get fetch data)TypeError:res.json 不是函数(无法获取数据)
【发布时间】:2022-01-01 15:10:20
【问题描述】:

我正在尝试使用 fetch API 获取响应,而不是陷入错误,如下所述。这是我的代码

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

错误: TypeError:res.json 不是函数 承诺 {} 显示待处理

【问题讨论】:

  • 您需要await in const res = await fetch(...)

标签: javascript reactjs json express


【解决方案1】:

你需要awaitfetch语句,然后调用响应的.json方法。

const res = await fetch(...)

data = await res.json();

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

【讨论】:

【解决方案2】:
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')
    }
}

【讨论】:

  • 我认为没有必要等待res.json,因为它不是一个承诺。
  • res.json() 是一种返回承诺的方法。因此,您必须等待 JSON 数据。
  • 哦,好的。这是有道理的。
猜你喜欢
  • 2017-08-02
  • 2018-11-23
  • 2016-04-22
  • 1970-01-01
  • 2021-09-16
  • 2015-03-05
  • 2019-07-07
  • 2019-02-21
  • 2020-10-21
相关资源
最近更新 更多