我使用以下代码向我的 API 发出 HTTP 请求:
fetch('api/register', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(jsonObj)
})
.then(response => {
responseClone = response.clone();
if (!response.ok) {
console.log(`HTTP ERROR STATUS CODE: ${response.status}`);
}
return response.json();
})
.then(function (data) {
processDataFromServer(data);
}, function (rejectionReason) {
console.log('JSON Parsing Error:', rejectionReason, responseClone);
responseClone.text()
.then(function (bodyText) {
console.log('Cannot parse as JSON:', bodyText);
});
})
.catch(error => {
console.log("Error: " + error)
deplayError(error);
});
代码有效!我想做的唯一更改是将
response.status
传递给我的 processDataFromServer(data)
函数。像processDataFromServer(data, response.status)
之类的东西。
由于 response.json()
是一个承诺,我无法同时将承诺和属性返回到我的下一个方法。知道如何做到吗?
如果您将代码重写为
async
函数并使用 await
,将会更容易。像这样的东西:
async function retrieve() {
try {
const response = await fetch('api/register', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(jsonObj)
});
const responseClone = response.clone();
if (!response.ok) {
console.log(`HTTP ERROR STATUS CODE: ${response.status}`);
}
try {
const data = await response.json();
processDataFromServer(data, response.status);
} catch (rejectionReason) {
console.log('JSON Parsing Error:', rejectionReason, responseClone);
const bodyText = await responseClone.text();
console.log('Cannot parse as JSON:', bodyText);
}
} catch (error) {
console.log("Error: " + error)
deplayError(error);
}
}
retrieve();