React:res.json()数据未定义

问题描述 投票:0回答:1

我在从提取API中获取数据时遇到问题。以前,当我在课程中进行“测试”时,它就可以正常工作。现在它在函数内部,当我尝试console.log(data)时,我得到“未定义”。 (请注意,API调用正在服务器上进行。console.log(res.json())返回数据。我是LOST。

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
  }
reactjs fetch
1个回答
0
投票

Arrow_functions

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

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

    .then(res => res.json())
© www.soinside.com 2019 - 2024. All rights reserved.