【发布时间】:2021-02-17 05:02:00
【问题描述】:
我在从我的云功能获取返回数据时遇到了一些麻烦,我现在只是尝试使用云功能将数据写入谷歌电子表格。以下是我目前的代码。
我有一个带有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() call not returning any data
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 函数,但我仍然不知道代码的哪一部分出错了,因为它们看起来与我在网上看到的其他代码示例几乎相同.当我从我的反应应用程序切换回 POST 时,我只会得到TypeError: Failed to fetch。
【问题讨论】:
-
检查它是否要去
.catch? -
@Ashish,嗯,我认为你是对的。我收到错误 TypeError: Failed to fetch 即使我已成功写入电子表格并从云功能日志中获得状态 200。老实说,我现在不确定是什么导致了这个错误。
-
请分享确切的错误消息以获得进一步的帮助。
-
它只返回 TypeError: Failed to fetch,可能类似于 stackoverflow.com/questions/49343024/… 但我没有收到返回响应。然后我尝试使用 POSTMAN 发帖,并且我成功地从云功能获得了响应,所以现在我不知道我的 react 应用程序出了什么问题。
标签: reactjs google-sheets-api fetch-api netlify-function