问题描述
我在从云功能获取返回数据时遇到了一些麻烦,我现在仅尝试将数据写入到具有云功能的Google电子表格中。下面是到目前为止我的当前代码。
我有一个带有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调用cloud函数,并成功获得状态200响应和消息。
所以我可以放心地认为问题不在于云函数,而在于获取函数,但是我仍然不知道代码哪一部分出错了,因为它们看起来与我在网上看到的其他代码示例几乎相同。从我的react应用切换回POST时,我只会得到TypeError: Failed to fetch
。
解决方法
将功能更改为此:
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})
});
}