我正在尝试对节点中的 json 服务器提供的 json 文件执行 POST 操作。我在尝试执行上述 POST 操作时收到以下 500 错误:
“类型错误:无法读取未定义的属性“id” 在 Function.createId"
后期操作如下:
pushState = () => {
var update = {
"a": 1,
"b": 2
};
return fetch(url, {
mode: 'cors',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(update)
})
.then((response) => {
console.log(response);
response.text();
})
.then((responseData) => {
console.log("Response:",responseData);
}).catch((error) => {
console.log(error);
})
.done();
}
我是否正确执行了 POST 请求?
编辑:添加异步和等待后,我仍然收到相同的错误:
pushState = async () => {
var update = {
"a": 1,
"b": 2
};
var result = await fetch(url, {
mode: 'cors',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(update)
})
.then((response) => {
console.log(response);
return response;
})
.catch((error) => {
console.log(error);
});
return result;
}
最佳答案
这里有两个问题:
- 您没有从
fetch
返回任何内容。 fetch
是异步的。按照您现在使用pushState
立即返回结果来调用它的方式,当您遇到错误时,它几乎总是返回undefined
。您需要使用 async/await 编写pushState
。
编辑以回答评论:
由于您使用的是函数箭头语法,因此使 pushState
异步将如下所示:
pushState = async () => { /* code */ }
为了帮助您了解 fetch
的工作原理,我建议阅读 this first 。然后,要从高层次理解 async/await,请阅读 this article 。您生成的代码将如下所示:
pushState = async () => {
var update = {
"a": 1,
"b": 2
};
var result = await fetch(...) // Remember to return something.
return result;
}
关于javascript - 无法在 React Native 中使用 fetch 执行 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44811809/