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