Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda