Node.js表单值始终返回' undefined'

时间:2017-11-29 06:10:59

标签: node.js forms validation express

我见过类似的问题,不幸的是我没有足够的代表留下一个小评论,所以我不得不提出一个新问题。

在我的注册表单中,我提交的FirstName和LastName值总是会返回undefined,这很奇怪,因为即使我提交的表单都是空的,这两个是唯一返回undefined的字段。这是我的路线文件夹

/routes/main.js

router.post('/register', function(req, res){
  var firstName = req.body.FirstName;
  var lastName = req.body.LastName;
  var email = req.body.email;
  var username = req.body.username;
  var password = req.body.password;
  var cpassword = req.body.cpassword;

//Validation
req.checkBody('firstName', 'First name is required!').notEmpty();
req.checkBody('lastName', 'Last name is required!').notEmpty();
req.checkBody('email', 'E-mail is invalid!').isEmail();
req.checkBody('username', 'Username is required!').notEmpty();
req.checkBody('password', 'Password is required!').notEmpty();
req.checkBody('cpassword', 'Passwords do not match!').equals(password);


var errors = req.validationErrors();

if(errors){
    res.render('register', {
        errors: errors
    });
    console.log('there are form errors');
    console.log(errors);
    console.log(firstName);
    console.log(lastName);
} else {
    console.log('no errors');
}

和标记

<h2>Student Registration</h2>
<form method="post" action="/register">
<div class="form-group">
    <label for="">First Name</label>
    <input type="text" class="form-control" placeholder="First Name" name="FirstName">
</div>
<div class="form-group">
    <label for="">Last Name</label>
    <input type="text" class="form-control" placeholder="Last Name" name="LastName">
</div>
<div class="form-group">
    <label for="">Username</label>
    <input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
    <label for="">E-mail</label>
    <input type="text" class="form-control" placeholder="email" name="email">
</div>
<div class="form-group">
    <label for="">Password</label>
    <input type="Password" class="form-control" name="password">
</div>
<div class="form-group">
    <label for="">Confirm Password</label>
    <input type="Password" class="form-control" placeholder="ConfirmPassword" name="cpassword">
</div>
<button type="submit" class="">Register</button>
</form>

让我感到困惑的是,当我在console.log中时,我看到了名字和姓氏值,但它们的值仍未定义。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您的验证中有错字。在您的表单中,您提交了FirstNameLastName,但在验证过程中,您正在检查firsNamelastName