Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!