Estoy tratando de crear un punto final que actualice un archivo mediante una solicitud posterior y luego lo redireccione a la página de inicio. Pero la redirección no funciona.
Sin embargo, cuando comento 'await sendMsg()', la redirección funciona bien.
¿Podría ayudarme a detectar y solucionar el problema?
¡Gracias por adelantado!
app.get('/add', async function(req, res){ await sendMsg(); res.redirect('/'); }); app.post('/update', async function(req, res){ const {data} = req.body; async function writeData(data) { try { return fs.writeFileSync(__dirname + '/config/' + 'task.json', JSON.stringify(data), 'utf8'); } catch (err) { console.log('Problem writing to file.') } } await writeData(data); }); async function sendMsg(){ var pURL = 'http://localhost:6500/update'; ... ... await fetch(pURL, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({data:config}) }) .catch(err => console.log(err)); }Para esperar una función, necesita que esa función devuelva una promesa. Necesita que sendMsg() se complete antes de poder redirigir.
app.get('/add', async function(req, res){ try{ await sendMsg(); res.redirect('/'); }catch(e){ //Error in sendMsg() console.log(e) } }); async function sendMsg(){ return new Promise((resolve, reject)=>{ var pURL = 'http://localhost:6500/update'; ... ... fetch(pURL, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({data:config}) }) .then(response => { // <---------- Little Change ---------- resolve() }) .catch(err => { console.log(err) reject() }); }) }¡Gracias a todos!
Olvidé poner res.end() al final de la API de publicación de 'actualización'.
Gracias por la ayuda.
El código de trabajo:
app.get('/add', async function(req, res){ try { await sendMsg(); } catch(e) { console.log(e); } res.redirect('/'); }); app.post('/update', async function(req, res){ const {data} = req.body; async function writeData(data) { try { return fs.writeFileSync(__dirname + '/config/' + 'task.json', JSON.stringify(data), 'utf8'); } catch (err) { console.log('Problem writing to file.') } } await writeData(data); res.end(); }); async function sendMsg(){ return new Promise((resolve, reject)=>{ var pURL = 'http://localhost:6500/update'; ... ... fetch(pURL, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({data:config}) }) .then(response => { // <---------- Little Change ---------- resolve() }) .catch(err => { console.log(err) reject() }); }) }