Así que estoy haciendo una solicitud a un punto final de API. Cuando JSONBody que es la variable data que se pasa a POSTRequest(), obtengo el JSON que creé impreso en el registro; sin embargo, cuando pruebo JSON.Stringify(), ¿me devuelven un objeto vacío?
Me preguntaba qué estoy haciendo mal y cómo solucionarlo :)
getFileData()
const getFileData = () => { var data = {} // DO SOME STUFF HERE TO data POSTRequest(data); }POSTSolicitud()
const POSTRequest = async (JSONBody) => { console.log(JSONBody) console.log(JSON.stringify(JSONBody)) try { const response = await fetch(API_ENDPOINT, { method: 'POST', body: JSON.stringify(JSONBody), headers: { 'Content-Type': 'application/json' } }); response.json() .then(function (res) { Promise.resolve(res) .then(function (finalData) { console.log(finalData); props.setData(finalData); }); }); } catch (error) { console.log(error); } }No está esperando la respuesta de la llamada de búsqueda correctamente, intente esto:
const POSTRequest = async (JSONBody) => { console.log(JSONBody) console.log(JSON.stringify(JSONBody)) await fetch(API_ENDPOINT, { method: 'POST', body: JSON.stringify(JSONBody), headers: { 'Content-Type': 'application/json' } }).then((response) => { console.log(response); props.setData(response); }).catch((error) => { console.log('POSTRequest error: ' + error) }) });