Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
Node.JS problem redirecting to new api endpoint after calling function

I'm trying to create an endpoint that updates a file using a post request, then redirects back to the home page. But the redirect isn't working.

However, when I comment out 'await sendMsg()', the redirect works fine.

Could you help me spot and fix the problem?

Thanks in advance!


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));

}

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

To await a function you need that function to return a promise. You need for sendMsg() to complete before you can redirect.

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()
      });

    })

}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Thanks everyone!

I forgot to put res.end() at the end of the 'update' post API.

Thanks for the help.

The working code:


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()
      });

    })

}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda