I want to fetch a get request to my spring boot server, and i get my json back, but when i want to return it, there is an undefined error. I am new to Javascript, so the answer is probably obvious, but i cant find it!
Sry for bad english and thanks in regards!
Code:
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
});
}
Edit with async, still does not work: 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;
});
}
This is my react component function:
function Admin(){
const data = httpGet('https://jsonplaceholder.typicode.com/users'); // Not Working
console.log(data);
return(
<div>
<h1> Admin Page</h1>
</div>
)
}
function httpGet(theUrl) {
return fetch(theUrl, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json());
}
(async() => {
const response = await httpGet('https://jsonplaceholder.typicode.com/users');
console.log(response);
})();