【问题标题】:Is there any way to run a query after 30 mins in node.js?有什么方法可以在 node.js 中 30 分钟后运行查询?
【发布时间】:2020-05-27 18:32:12
【问题描述】:

我正在编写一个网站,我将在 3 次尝试后禁止用户 30 分钟,但是使用 setTimeout 方法似乎不起作用这是我的代码:

let isOnce = true;
router.post('/login', (req, res, next) => {
    const { email, password } = req.body;
    User.findOne({ email: email }, (err, user) => {
        if (err) {
            console.log(err);
        }
        if (user.savedAttempts < 3) {
            passport.authenticate('local', {
                successRedirect: '/users/questions',
                failureRedirect: '/users/login',
                failureFlash: true
            })(req, res, next);
            attempts += 1;
            isOnce = true;
        } else {
            setTimeout(() => {
                if (isOnce == true) {
                    User.updateOne({ email: email }, { $inc: { savedAttempts: 1 } }, (err, resp) => {
                        if (err) console.log(err);
                    });
                }
                isOnce = false;
                res.redirect("/users/login");
            }, 1800000);
        }
    });
});

任何帮助将不胜感激。

【问题讨论】:

  • 通过设置user.bannedUntil = new Date().getTime() + 1800000; 来禁止用户并将其保存到数据库可能会更容易。然后当用户尝试登录时检查是否没有被禁止。

标签: node.js mongodb express authentication wait


【解决方案1】:

我不认为你对 setTimeout 的理解是正确的。它的作用是在一段时间后执行函数

实现该行为的更好方法是存储他第三次尝试的时间戳,并将其与 Date.now() 进行比较以检查 30 分钟的禁令期是否已过

【讨论】:

  • 感谢您的建议,它现在正在工作,但我还有另一个问题,我应该尝试 3 次,但由于这是一个帖子请求,我有一个额外的尝试,但没有任何作用,您能给我一个建议吗那也是?谢谢
猜你喜欢
  • 1970-01-01
  • 2021-10-25
  • 2016-08-31
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多