JSON.stringify()不起作用,但console.log()返回JSON



所以我正在向API端点发出请求。当我打印JSONBody(传递给POSTRequest((的变量data(时,我会将我创建的JSON打印到日志中,但当我尝试使用JSON.Stringify((时,会返回一个空对象?

我只是想知道我做错了什么以及如何修复:(

getFileData((

const getFileData = () => {
var data = {}
// DO SOME STUFF HERE TO data
POSTRequest(data);
}

POSTRequest((

const POSTRequest = async (JSONBody) => {
console.log(JSONBody)
console.log(JSON.stringify(JSONBody))
try {
const response = await fetch(API_ENDPOINT, {
method: 'POST',
body: JSON.stringify(JSONBody),
headers: { 'Content-Type': 'application/json' }
});
response.json()
.then(function (res) {
Promise.resolve(res)
.then(function (finalData) {
console.log(finalData);
props.setData(finalData);
});
});
} catch (error) {
console.log(error);
}
} 

如果没有正确等待fetch调用的响应,请尝试以下操作:

const POSTRequest = async (JSONBody) => {
console.log(JSONBody)
console.log(JSON.stringify(JSONBody))
await fetch(API_ENDPOINT, {
method: 'POST',
body: JSON.stringify(JSONBody),
headers: { 'Content-Type': 'application/json' }
}).then((response) => {
console.log(response);
props.setData(response);
}).catch((error) => {
console.log('POSTRequest error: ' + error)
})
});

最新更新