0

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

这是我的代码:

app.js

//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;

user.js

//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;

register.ejs

//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>

Error

ReferenceError: /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/views/register.ejs:5
    3| <div class="container">
    4| 
 >> 5|     <% if(errors){errors.forEach(function(error){%>
    6| 
    7|     <div class="alert alert-danger"><%= error.msg %></div>
    8| 
 
errors is not defined
    at eval (eval at compile (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:549:12), <anonymous>:22:8)
    at returnedFn (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:580:17)
    at tryHandleCache (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:223:34)
    at View.exports.renderFile [as engine] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:437:10)
    at View.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/view.js:127:8)
    at tryRender (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/application.js:640:10)
    at Function.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/response.js:971:7)
    at /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/routes/users.js:12:9
    at Layer.handle [as handle_request] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/layer.js:95:5)
    at /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:275:10)

4

4 回答 4

2

那是因为您正在尝试访问一个不存在的变量,请注意,errors如果您的表单中存在验证错误,则该变量仅生成并返回到视图,否则它是未定义的,这就是为什么在您的情况下您必须检查errors变量是否存在,例如这个:

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

注意:typeof 操作符返回一个字符串:变量的类型,如果变量没有声明则返回 undefined

于 2017-11-29T18:11:49.700 回答
1
npm uninstall express-validator --save
npm install express-validator@2.20.8 --save
于 2021-01-28T08:11:59.810 回答
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}));
于 2018-07-24T07:43:03.280 回答
0
<% if(locals.errors){locals.errors.forEach(function(error){%>
    <div class="alert alert-danger"><%= error.msg %></div>
<% })} %>
于 2018-09-15T10:41:24.153 回答