Quiero obtener una solicitud de obtención para mi servidor de arranque Spring, y recupero mi json, pero cuando quiero devolverlo, hay un error indefinido. Soy nuevo en Javascript, por lo que la respuesta probablemente sea obvia, ¡pero no puedo encontrarla!
Sry por mal inglés y gracias en lo que respecta!
Código:
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 }); }Edite con async, todavía no funciona: 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; }); }Esta es mi función de componente de reacción:
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); })();Puede hacer esto con async y await , lo que facilita la escritura y comprensión del código.
Aquí está la muestra, que puede utilizar.
const httpGet = async (theUrl) => { const response = await fetch(theUrl, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json" } }); return response.json(); }; // calling the method (async () => { const data = await httpGet("https://jsonplaceholder.typicode.com/posts/1") console.log("response data is: ", data) })()