I'm building a website to collect data for my writing research using javascript and node js. On the client side, I use fetch function to get the data and send a post request to the server side. On the server side, I have the data saved in my MongoDB database. Because it usually takes 5 to 15 seconds for the server to handle the posted data, I would like to use a redirect function to redirect the user on the client side to a new page when the posted data are successfully saved. In this way, the user of the webpage cannot go to the next page until the post request is successfully processed. But for some reason, the redirect function doesn't work. Can anybody help with this?
Here are the code snippets on the client side:
//post the data to the serve
button.onclick = () => {
const options = {
method: 'POST',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify(keylog)
};
fetch('/api6', options);
};
Here are the relevant codes on the server side:
app.post('/api6', (req, res) =>{
let data = req.body;
let writing = new Writing({
Task: 'Writing',
ParticipantID: JSON.stringify(data.ParticipantID),
Prompt: JSON.stringify(data.Prompt),
TaskOnSet: JSON.stringify(data.TaskOnSet),
TaskEnd: JSON.stringify(data.TaskEnd),
PageLeaveStart: JSON.stringify(data.PageLeaveStart),
PageLeaveEnd: JSON.stringify(data.PageLeaveEnd),
InactivityStart: JSON.stringify(data.InactivityStart),
InactivityDuration: JSON.stringify(data.InactivityDuration),
EventID: JSON.stringify(data.EventID),
Time: JSON.stringify(data.Time),
Output: JSON.stringify(data.Output),
Cursorposition: JSON.stringify(data.Cursorposition),
WordCount: JSON.stringify(data.WordCount),
TextChange:JSON.stringify(data.TextChange),
Activity: JSON.stringify(data.Activity),
FinalProduct: JSON.stringify(data.FinalProduct)
});
writing.save();
res.redirect('/vocab_intro');
});
app.get('/vocab_intro', (req, res) => {
res.sendFile('./vocab_intro/index.html',
{root: __dirname});
});