无法使用Express-validator验证用户输入

时间:2019-01-04 08:22:18

标签: javascript node.js mongodb

我附上了注册表格和验证码(Node.js),如下所示。我已经尝试验证来自注册表单的用户输入,但是还没有成功!但是它已成功存储在MongoDB数据库中。

<form  action="/register" method="POST">
  <input type="text" name="name" placeholder="username"><br>
  <input type="password" name="userpass" placeholder="password"><br>
  <input type="submit" name="submit" value="send">
</form>

router.post('/register', function(req, res, next) {
// Get user input from register form
let nam = req.body.name;
let pass = req.body.userpass;

req.checkBody('nam', 'Name is required').notEmpty();
req.checkBody('pass', 'Pass is required').notEmpty();

var errors = req.validationErrors();
if(errors){
   console.log(errors)
}
else {
   var newUser = new User({
     username:nam,
     pass:pass
   });
   User.createUser(newUser,function(err,user){
          if(err) throw err;
          console.log(user);
   });
   res.location('/register');
   res.redirect('/register');
}

我在运行代码时得到了这个结果。

GET /register 304 25.699 ms - -
[ { param: 'nam', msg: 'Name is required', value: undefined },
{ param: 'pass', msg: 'Pass is required', value: undefined } ]

1 个答案:

答案 0 :(得分:1)

下面的代码应该可以工作,我认为主要问题是使用实际的表单变量名称(名称,用户密码):

index.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');

app.use(express.static('./'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());

var router = express.Router();
app.use("/", router);

router.post('/register', function(req, res, next) {
    console.log('/register POST body: ', req.body);

    /* Check form variables. */
    req.checkBody('name', 'Name is required').notEmpty();
    req.checkBody('userpass', 'Pass is required').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        console.error("Validation errors occurred: ", errors);
        res.status(400).json({ status: "Bad Request" });
        return;
    }

    console.log("Validation successful");

    // Get user input from register form
    let nam = req.body.name;
    let pass = req.body.userpass;

    var newUser = new User({
        username:nam,
        pass:pass
    });
    User.createUser(newUser,function(err,user){
            if(err) throw err;
            console.log(user);
    });
    res.location('/register');
    res.redirect('/register');
});

app.listen(3000);

index.html

<!doctype html>
<html lang="en">
    <body>
    <form  action="/register" method="POST">
        <input type="text" name="name" placeholder="username"><br>
        <input type="password" name="userpass" placeholder="password"><br>
        <input type="submit" name="submit" value="send">
    </form>
    </body>
</html>