【问题标题】:React: res.json() data is undefined反应:res.json() 数据未定义
【发布时间】:2020-06-07 03:36:38
【问题描述】:

我在从我的 fetch API 获取数据时遇到问题。当我在课堂上进行“测试”时,它以前是有效的。现在它在函数内部,当我尝试 console.log(data) 时,我得到“未定义”。 (注意,API 调用正在服务器上运行。console.log(res.json()) 返回一个数据。我迷路了。

const test = () => {
    fetch('/api/test/', {
      method: "post",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },

      //make sure to serialize your JSON body
      body: JSON.stringify({zip: val})
    })
    .then(res => { res.json()}) //THIS RETURNS OK
    .then(data => {console.log({data})}) //THIS IS WHERE I HAVE PROBLEMS
  }

编辑:

我也试过了

.then(data=> {console.log(data)})

.then(data => {console.log([data])})

我有什么遗漏吗?

【问题讨论】:

    标签: reactjs fetch


    【解决方案1】:

    Arrow_functions

    您应该返回 res.json() 才能成功工作;

        .then(res => { return res.json()})
    

        .then(res => res.json())
    

    【讨论】:

    • 你好艾哈迈德!我目前正在使用 .then(res => {return res.json()}) 我是堆栈溢出的新手,并且在将代码放入哈哈时犯了一个错误。我更新了帖子以反映我的经历。谢谢!
    • 你好亲爱的,你仍然使用“.then(res => { res.json()})”。请更新您的代码并再次测试。它将成功运行。使用这个功能我相信它会工作pastebin.com/j7DVZjW3
    • 感谢您的耐心等待。或许有误会。我目前正在使用 .then(res => { res.json()}) .then(data => {console.log({data})}) 你是说我需要使用 .then(res => { res.json()}) 两次? .then(data....) 是我遇到问题的地方。 .then(res...) 工作正常
    • @shadow_code 要获取data,您需要在上一步中返回res.json().then(res => { res.json()})(带 {})不会返回 res.json().then(res => res.json())(不带 {})会。
    • Promise 就像管道一样。 first .then() 返回值到 next .then() 所以如果 first .then() 不返回任何值。下一个 .then() 数据将是未定义的。成功地工作。你应该在第一个 .then() 中返回 res.json();
    猜你喜欢
    • 2019-08-25
    • 2018-11-18
    • 2014-09-18
    • 2018-07-06
    • 1970-01-01
    • 2018-08-04
    • 2021-05-31
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多