首页 > 解决方案 > 几秒钟后自动渲染页面

问题描述

我想创建一个测验应用程序,其中每秒分配的时间为 10 秒。用户必须在文本框中写下答案,然后单击提交继续。但是这里10秒后,即使用户没有提交答案,我也要他去下一页。我尝试使用 setTimeout 但它没有用。

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

这是模板页面的发布请求。

那么问题来了,如何在不点击客户端页面的提交按钮的情况下调用post请求函数呢?

标签: node.jstimerhttp-postbackend

解决方案


setTimeout 方法似乎对我有用。

前端:

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

后端:

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

推荐阅读