首页 > 解决方案 > Fetch().then() 不返回数据

问题描述

我在从我的云功能获取返回数据时遇到了一些麻烦,我现在只是想用云功能将数据写入谷歌电子表格。以下是我目前的代码。

我有一个按钮,onClick={this.AddRecord}然后可以调用云功能

AddRecord = async () => {

    await fetch(url, {
        method: 'POST',
        body: JSON.stringify({
            date: this.getDate(),
            name: this.state.name,
            number: '\'' + this.state.number
        })
    })
    .then((response) => {return response.json()})
    .then((data) => {
        alert(data)         // this never gets executed
        this.setState({message:data})
    })
    .catch((err) => {
        this.setState({message: err})
    });
}

这是我的云函数 POST 处理程序:

case 'POST':
   /* parse the string body into a usable JS object */
   const data = JSON.parse(event.body);

   const addedRow = await sheet.addRow(data);

   return {
      statusCode : 200,
      body: JSON.stringify({
         message : 'Posted successfully.',
         rowNumber: addedRow._rowNumber - 1 // minus the header row
      })
   };

如果有人能指出我正确的方向,我将不胜感激,因为我花了很多时间尝试调试它但无济于事。

到目前为止我读过的一些资源:

fetch() 调用不返回任何数据

https://www.smashingmagazine.com/2020/06/rest-api-react-fetch-axios/

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

编辑:

我尝试通过 POSTMAN 调用云功能并成功获得带有消息的状态 200 响应。 邮递员测试

所以我可以安全地假设问题不在于云函数,而是 fetch 函数,但我仍然不知道代码的哪一部分出错了,因为它们看起来与我在网上看到的其他代码示例几乎相同。TypeError: Failed to fetch只有当我从我的反应应用程序切换回 POST 时,我 才会得到。获取错误

标签: reactjsgoogle-sheets-apifetch-apinetlify-function

解决方案


将您的功能更改为:

AddRecord = async () => {

    await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type':'application/json' }, // here is the change
        body: JSON.stringify({
            date: this.getDate(),
            name: this.state.name,
            number: '\'' + this.state.number
        })
    })
    .then((response) => response.json())
    .then((data) => {
        alert(data)       
        this.setState({message:data})
    })
    .catch((err) => {
        this.setState({message: err})
    });
}

推荐阅读