Search code examples
node.jstimerhttp-postbackend

Rendering a page after some seconds automatically


I wanted to create a quiz application where the allocated time for each second is 10 seconds. The user have to write the answer in the text box and click submit to go forward. But here after 10 seconds, even if the user doesn't submit the answer, I want him to go to the next page. I tried using the setTimeout but it didn't work.

app.post("/template", function (req, res) {
  ans = req.body.answer;
  console.log(ans);
  setTimeout(function () {
    res.render("done", { answer1: ans });
  }, 2000);
  
});

This was the post request for the template page.

So the question is how to call the post request function without clicking the submit button on the client page?


Solution

  • The setTimeout method seems to work for me.

    Frontend:

     setTimeout(() => {
      const answer = "B";
      axios.post("http://localhost:5000/template", { answer });
    }, 10000);
    

    Backend:

    const express = require("express");
    const cors = require("cors");
    const app = express();
    app.use(cors());
    app.use(express.json());
    app.listen(5000, () => console.log("listening on port 5000"));
    
    app.post("/template", (req, res) => {
      const ans = req.body.answer;
      res.render("done", { answer1: ans });
    });