我遇到了一个非常奇怪的问题。此 javascript 代码应该使用 GET 请求从后端获取对象。我收到的 header 的状态为 200,但正文似乎是空的。
function GetAssignment() {
assignment = fetch(GetAssignmentURL,
{
method: 'GET',
headers: {
'Accept': 'application/json',
}
})
.then((response) => {
if (response.status == 200) {
console.log(response);
return response.json();
}
else
{
throw `error with status ${response.status}`;
}
})
.catch((exception) => {
console.log(exception);
});
}
回复:
/image/B3pfo.png
现在,我用 Postman 尝试了同样的事情,它在这里工作得很好。 (我检查了调用后端的 URL,它在 Postman 中和在 Javascript 中完全一样,所以错误并不存在。)
结果:
/image/H6Pnm.png
所以,我想知道我的 Javascript 代码有什么问题。我调试了后端,当我使用 Javascript 调用它时,它确实返回了一个对象,就像它应该的那样。我一直以这种方式完成 GET 请求,但现在突然之间,响应主体在我的应用程序的前端被阻塞了。
有没有人遇到过同样的问题?
最佳答案
您显示的代码中没有任何内容实际上是在使用正文。您正在登录 response
在你告诉它阅读正文之前,你的 assignment
变量只有 fetch
的 promise ,它不会尝试对它做任何事情。
要查看正文,您需要查看 json
中的 Promise 的履行值(它将做两件事:1. 读取正文,2. 从 JSON 中解析它)。
例如:
function GetAssignment() {
fetch(GetAssignmentURL, // *** No `assignment =` on this line
{
method: 'GET',
headers: {
'Accept': 'application/json',
}
})
.then((response) => {
if (response.status == 200) { // *** This can be just `if (response.ok) {`
console.log(response); // *** This is premature
return response.json();
}
else
{
throw `error with status ${response.status}`;
}
})
.then(assignment => { // ***
// ...use `assignment` here... // ***
}) // ***
.catch((exception) => {
console.log(exception);
});
}
但是:如果目标是交流assignment
对于调用函数的代码,您需要返回 promise 链,如下所示:function GetAssignment() {
return fetch(GetAssignmentURL,
{
method: 'GET',
headers: {
'Accept': 'application/json',
}
})
.then((response) => {
if (response.status == 200) { // *** This can be just `if (response.ok) {`
console.log(response); // *** This is premature
return response.json();
}
else
{
throw `error with status ${response.status}`;
}
});
}
使用它的代码会像这样使用它:GetAssignment()
.then(assignment => {
// ...use `assignment` here...
})
.catch(error => {
// handle/report error
});
旁注:如果
GetAssignment
不打算用 new
调用,JavaScript 中最普遍的约定是它以小写字母开头:getAssignment
.只是把它放在那里,因为 ES2018 是几年前的事了,在现代环境中(或者如果你正在编译)你可以使用
async
函数,这使您可以编写逻辑而不必担心时间问题。 async
函数返回 promise ,并让你使用 await
在等待 promise 解决时暂停您的逻辑:async function getAssignment() {
const response = await fetch(GetAssignmentURL, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
if (!response.ok) {
throw `error with status ${response.status}`;
}
return response.json();
}
在上面,对 fetch
的调用同步发生,但随后函数暂停自身等待结果并返回一个 promise 。它返回的 promise 将根据它所发生的 promise 来解决await
s。最终,一切都好,它的 promise 会兑现你的值(value) return
(或者在上述情况下,履行值(value) response.json()
在结算时提供)。你会像这样使用它(在另一个
async
函数中):const assignment = await getAssignment();
// ...use `assignment` here...
(如果出现错误,上面代码所在的 async
函数将拒绝该 promise )
关于javascript - Fetch API - 状态为 200 的 GET 请求返回空正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61834626/