【发布时间】:2021-11-14 21:02:01
【问题描述】:
我想向我的 Spring Boot 服务器获取一个 get 请求,然后我取回了我的 json,但是当我想返回它时,出现了一个未定义的错误。我是 Javascript 新手,所以答案可能很明显,但我找不到!
抱歉英语不好,谢谢!
代码:
function httpGet(theUrl)
{
fetch(theUrl,
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then (response => response.json())
.then(response => {
console.log(response); // Logs the json array
return response; // Returns undefined
});
}
使用异步编辑,仍然不起作用: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
async function httpGet(theUrl)
{
const response = await fetch(theUrl,
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
const jsonResponse = await response.json()
.then(data => {
return data;
});
}
这是我的 react 组件函数:
function Admin(){
const data = httpGet('https://jsonplaceholder.typicode.com/users'); // Not Working
console.log(data);
return(
<div>
<h1> Admin Page</h1>
</div>
)
}
【问题讨论】:
-
返回
fetch本身。像这样写下return fetch (theurl, ...)。 -
这将返回一个未定义的挂起
-
这会返回一个承诺,因此您需要为此使用
asyncawait。了解更多信息:developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/…
标签: javascript fetch fetch-api