首页 > 解决方案 > 防止复选框输入条件的无限循环

问题描述

我有一个表单提交过程,其中我有带有 if/else 语句的中间件在触发我的身份验证控制器之前验证值是否存在,但由于某种原因,我的复选框输入字段ERR_TOO_MANY_REDIRECTS在表单提交时触发,即使我尝试加载表单提交后的页面。我检查的原因undefined是因为我注意到如果未检查该值,则正文不包含此输入。是否有更好的条件来检查是否检查了此值以消除我看到的重定向循环?有没有办法将此中间件设置为仅在路由的 POST 部分触发?

我用于的中间件/sign-up

siteRoutes.use('/sign-up', function(req, res, next){
    console.log("Sign Up Use")
    console.log(req.body);
    models.User.findOne({
        where: {
            email: req.body.email
        }
    }).then(function(existingUser) {
    if (existingUser){
        req.flash('error', 'Email already exists.');
        return res.redirect('/sign-up');
    } else if (req.body.termsOfService === undefined) {
        console.log("TOS Check")
        req.flash('error', 'Accept terms');
        return res.redirect('/sign-up');
    } else {
        console.log("Next")
        next();
    }
    });
});

输入字段:

   <input type="text" class="form-control" id="sign-up-fist-name"  name="firstName" value="" placeholder="First Name">
                <br />
                    <input type="text" class="form-control" id="sign-up-last-name"  name="lastName" value="" placeholder="Last Name">
                <br />
                    <input type="text" class="form-control" id="sign-up-username"  name="email" value="{{user.email}}" placeholder="Email Address">
                <br />
                    <input type="password" class="form-control" id="sign-up-password"  name="password" value="" placeholder="Password">
                <br />
                    <input type="password" class="form-control" id="sign-up-confirm-password"  name="confirmPassword" value="" placeholder="Confirm Password">
                <br />
                    <label>
                        <input type="checkbox" name="termsOfService"> I confirm that I have read, consent and agree to Synotate's <a href="/terms-of-service">Terms of Service</a> and <a href="privacy-policy">Privacy Policy</a>
                    </label>

标签: javascriptexpresscheckbox

解决方案


用于req.method确定请求是GET还是POST

更改req.body.termsOfService === undefinedreq.method === 'POST' && req.body.termsOfService === undefined

另一种方法是使用siteRoutes.getsiteRoutes.post而不是siteRoutes.use


推荐阅读