Tengo una tarea que requiere que obtenga datos de una API de terceros (itunes) para buscar contenido que proporciona la API de terceros. La API de terceros será manejada por el backend (Express y Node). Ahora, cuando hago clic en un botón (desde reaccionar), quiero enviar primero una solicitud POST (usando fetch), ESPERAR hasta que finalice la solicitud POST, luego recuperar los datos (Ejecutar la solicitud GET)...
En otras palabras: quiero hacer el segundo método de obtención (solicitud de obtención), esperar hasta que el primer método de obtención (solicitud posterior) termine de ejecutar/publicar datos. Solo entonces se puede ejecutar la solicitud de obtención.
Enlace al código JS (Reaccionar):
async function postReq() { return await fetch('http://localhost:3001/', { method: "POST", headers:{ "Content-Type": "application/json" }, body: JSON.stringify(userData) }) } const fetchData = (e) =>{ e.preventDefault(); postReq(); fetch('http://localhost:3001/api') .then((response)=> response.json()) .then((data)=>{ //console.log(data) sessionStorage.setItem(`${mediaType}`, JSON.stringify(data)) }) }Enlace al código JS (Express/Node):
app.post('/', (req, res, next)=>{ //console.log("hii", req.body.search) fetch(`https://itunes.apple.com/search?term=${req.body.search}&entity=${req.body.mediaType}&limit=8`).then( (response)=> response.json() ).then( (data)=>{ console.log(data) fs.writeFile("data.json", JSON.stringify(data), (err)=>{ if(err) throw err }) } ) }) //when server receives GET request we want to server the data that was fetched,back to the user app.get('/api', (req, res, next)=>{ fs.readFile("data.json", (err, data)=>{ if(err) throw err; //console.log(JSON.parse(data)) res.json(JSON.parse(data)); }) })Puede esperar a que se complete la solicitud de publicación y luego llamar a GET api.
async function postReq() { return await fetch('http://localhost:3001/', { method: "POST", headers:{ "Content-Type": "application/json" }, body: JSON.stringify(userData) }) } const fetchData = (e) =>{ e.preventDefault(); postReq().then(data=>{ fetch('http://localhost:3001/api') .then((response)=> response.json()) .then((data)=>{ //console.log(data) sessionStorage.setItem(`${mediaType}`, JSON.stringify(data)) }) }); }app.post('/', async (req, res, next)=>{ const data = await fetch(`https://itunes.apple.com/search?term=${req.body.search}&entity=${req.body.mediaType}&limit=8`); await fs.writeFile("data.json", JSON.stringify(data)); const updatedFile = fs.readFile('data.json'); res.json(updatedFile); // it will respond to your POST request with updated file. // res.redirect('/api') /* Or you can redirect to a certain route after POST method */ }) app.get('/api', async (req, res, next)=>{ const file = await fs.readFile("data.json"); res.json(file); })