nodejs:在ejs模板中未定义的express-validator错误

时间:2017-11-29 06:22:54

标签: node.js express ejs express-validator

我使用的是ejs引擎而不是哈巴狗。当我单击注册按钮时,我在寄存器视图中未定义错误。我只能获得验证消息的可能性很小,但是当我单击其他链接然后再返回到注册页面时,再次出现相同的错误。

这是我的代码:

<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/dd_root_view" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/dd_content_login" /> <android.support.design.widget.FloatingActionButton android:id="@+id/dd_fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@mipmap/dd_icon_checkmark" /> </android.support.design.widget.CoordinatorLayout>

&#13;
&#13;
app.js
&#13;
&#13;
&#13;

//app.js code var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var passport = require('passport'); var expressValidator = require('express-validator'); var LocalStrategy = require('passport-local').Strategy; var multer = require('multer'); var upload = multer({dest: './uploads'}); var flash = require('connect-flash'); var mongo = require('mongodb'); var mongoose = require('mongoose'); var db = mongoose.connection; var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Handle Sessions app.use(session({ secret:'secret', saveUninitialized: true, resave: true })); // Passport app.use(passport.initialize()); app.use(passport.session()); // Validator app.use(expressValidator({ errorFormatter: function(param, msg, value) { var namespace = param.split('.') , root = namespace.shift() , formParam = root; while(namespace.length) { formParam += '[' + namespace.shift() + ']'; } return { param : formParam, msg : msg, value : value }; } })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(flash()); app.use(function (req, res, next) { res.locals.messages = require('express-messages')(req, res); next(); }); app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;

&#13;
&#13;
user.js
&#13;
&#13;
&#13;

//user.js code var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multer({dest: 'uploads/'}); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('members', {page_name : 'members'}); }); router.get('/register', function(req, res, next) { res.render('register', { page_name: 'register' }); }); router.post('/register', upload.single('profileimage'), function(req, res) { var name = req.body.name; var username = req.body.username; var email = req.body.email; var password = req.body.password; var password2 = req.body.password2; if(req.file){ console.log("uploading file"); var profileimage = req.file.filename; } else{ var profileimage = "noimage.jpg"; } req.checkBody('name','Name field is required').notEmpty(); req.checkBody('email','Email field is required').notEmpty(); req.checkBody('email','Email is not valid').isEmail(); req.checkBody('username','Username field is required').notEmpty(); req.checkBody('password','Password field is required').notEmpty(); req.checkBody('password2','Passwords do not match').equals(req.body.password); // Check Errors errors = req.validationErrors(); //var errors = JSON.stringify(req.validationErrors()); if(errors){ console.log("errors: " + errors); res.render('register', {errors: errors}); } else{ console.log('No Errors'); res.render("/"); } }); router.get('/login', function(req, res, next) { res.render('login', { page_name: 'login' }); }); module.exports = router;

&#13;
&#13;
register.ejs
&#13;
&#13;
&#13;

//register.ejs code <%include layout%> <div class="container"> <% if(errors){errors.forEach(function(error){%> <div class="alert alert-danger"><%= error.msg %></div> <% })} %> <h4>register</h4> <form action="/users/register" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="exampleFormControlInput1">Name</label> <input type="text" class="form-control" name="name" placeholder="John"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Email address</label> <input type="email" class="form-control" name="email" placeholder="name@example.com"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Username</label> <input type="text" class="form-control" name="username" placeholder="username"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Password</label> <input type="password" class="form-control" name="password" placeholder="password"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Confirm Password</label> <input type="password" class="form-control" name="password2" placeholder="confirm password"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Profile Image</label> <input type="file" class="form-control" name="profileimage" > </div> <button type="submit" class="btn btn-primary">Register</button> </form> </div>

&#13;
&#13;
Error
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:2)

那是因为你试图访问一个非现有变量,请注意errors变量只生成并返回到视图中,如果表单中有验证错误,否则它是未定义的,这就是为什么在你的条件下你必须检查errors变量是否存在,如下所示:

 if (typeof errors !== 'undefined') { ...

注意:typeof运算符返回一个字符串:变量的类型,如果未声明变量,则返回undefined

答案 1 :(得分:1)

npm uninstall express-validator --save
npm install express-validator@2.20.8 --save

答案 2 :(得分:0)

看看我的代码,它正在工作

在文件“ index.js”中

/* GET home page. */
router.get('/', function(req, res, next) {

  res.render('index', { title: 'Home' , 
                        success:false, 
                        errors:req.session.errors ,
                        success:req.session.success });
  req.session.errors=null;
});
//////////////checking the form validation

router.post('/submit', function(req, res, next) {
req.check('email','Invalid Email Address!!!!!').isEmail();// it's an built in exprexx validator, but we can also write our own
req.check('password','Pssword lenght must be greater than 5!! ').isLength({min:5});
req.check('password','Password is not confirmed!!').equals(req.body.confirmpassword);
var errors=req.validationErrors();
if (errors){
  req.session.errors=errors;
  req.session.success=false;
}
else{
  req.session.success=true;
}
res.redirect('/');



});



module.exports = router;

在文件“ index.ejs”中

  <h1>Fill the form below..</h1><h1></h1>
            <h1>It's an example of Express Validator..</h1><h1></h1>



            <% if (success) { %>
                <h1><span class="badge badge-success">Congrats!! Form validation is secceded!!!</span></h1>

                <% } else { %>

                    <% if (errors) { %>

                        <div class="alert alert-danger" role="alert">
                                <h1><span class="badge badge-danger">Errors Occured!! </span></h1>

                                        <% errors.forEach(function(errors) { %>
                                            <h5><%= errors.msg %> </h5>


                     <% }); %>
                    </div>
                        <% } else { %>



                    <form action="/submit" method="POST">
                        <div class="form-row">
                          <div class="col-7">

                           <input type="email" class="form-control" id="email" placeholder="email" name="email">
                          </div>
                          <div class="col">

                            <input type="password" class="form-control" id="password" placeholder="password" name="password">
                          </div>
                          <div class="col">

                            <input type="password" class="form-control" id="confirmpassword" placeholder="confirmpassword" name="confirmpassword">
                          </div>
                        </div>
                        <h1></h1>
                        <button type="submit" class="btn btn-primary">Submit</button>
                      </form>
                      <% } %>
                    <% } %>

当然不要忘记在“ app.js”文件中添加以下行:

//adding validator and session
app.use(expressValidator());
app.use(expressSession({secret:'max',saveUninitialized:false,resave:false}));

答案 3 :(得分:0)

<% if(locals.errors){locals.errors.forEach(function(error){%>
    <div class="alert alert-danger"><%= error.msg %></div>
<% })} %>