reactjs - 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
})
};
如果有人能指出我正确的方向,我将不胜感激,因为我花了很多时间尝试调试它但无济于事。
到目前为止我读过的一些资源:
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 时,我
才会得到。
解决方案
将您的功能更改为:
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})
});
}
推荐阅读
- c - 如何使用微控制器在 C 中实现中断标志?
- awk - Unix/Perl/Python:大数据集上的替代列表
- x86 - 分支如何在来自微码定序器的代码中工作?
- laravel - 带有附加参数的 Laravel 语言前缀
- ms-word - Office JavaScript API:突出显示文档中的文本
- c# - 有没有办法计算重复的 xml 标记名并将每个标记名存储在不同的字典中?
- python - 如何将视频解码/编码为文本文件,然后返回视频?
- python - for循环前面的返回值
- metal - 调试金属着色器时,Xcode 是否支持 iPhone 中的着色器调试器?
- html - CSS Hover 仅适用于按钮的下半部分