Nodejs呈现视图和模板EJS

时间:2017-07-13 09:39:03

标签: node.js

关于渲染视图的两个问题,

为什么它不起作用?如果我将res.render放入if(错误),它不会呈现新网站,但仍然在当前页面上。 第二个问题是,如果我在ejs模板视图中,我把<%= errors%>显示错误,它是否有效,显示错误文件未找到

router.post('/create', function (req, res, next) {

  var newUser = {
    username: req.body.username,
    password: req.body.password
  }

  req.checkBody('username', 'Login is required').notEmpty();
  req.checkBody('password', 'Password is required').notEmpty();

  var errors = req.validationErrors();
    if(errors){

      console.log(errors)
        res.render('index',{
            errors:errors
    // console.log(errors)
    // res.send(errors);
        });
  } else {
    bcrypt.hash(newUser.password, saltRounds, function (err, hash) {
      if (err) {
        console.log(err)
      } else {
        newUser.password = hash;
        var user = new User(newUser);
        user.save()
          .then(function (User) {
            res.send(User);
          })
      }
    });
    req.flash('success_msg', 'You are registered and can now login');

    //res.redirect('/');
  }
});
控制台.log(错误)上的

  

[{param:'用户名',msg:'需要登录',值:undefined},     {param:'密码',       msg:'密码是必需的',       值:undefined}]

1 个答案:

答案 0 :(得分:0)

快速render方法也可以返回错误。使用回调来确定是否发生这种情况,并在发生else语句后添加一个返回停止逻辑。

var errors = req.validationErrors();

if(errors){
    return res.render('index', { errors: errors }, function (err, html) {
         if (err) console.error(err);
         res.send(html);
    });
}

bcrypt.hash(newUser.password, saltRounds, function (err, hash) {
      if (err) {
        console.log(err)
      } else {
        newUser.password = hash;
        var user = new User(newUser);
        user.save()
          .then(function (User) {
            res.send(User);
          })
      }
});

req.flash('success_msg', 'You are registered and can now login');
return res.redirect('/');

APP.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStategy = require('passport-local').Strategy;

var indexPage = require('./routes/index/index');
var productPage = require('./routes/product/product');
var userPage = require('./routes/user/user');
var categoryPage = require('./routes/category/category');
var filenotfound = require('./routes/error/error');

var mongoose = require('mongoose');

var Product = require('./model/product.model');
var Category = require('./model/category.model');
var User = require('./model/user.model');
var app = express();



mongoose.connect('mongodb://localhost/products', function (error) {
  if (error) {
    console.log('blad w polaczeniu')
  } else {
    console.log('connected');
    //=========================CONNNNNNECTTTTTTEEEEEEDDDDDDDDDDDDDDDD======================//


    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
    // parse application/json
    app.use(bodyParser.json());

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use('/assets', express.static('public'));


    // 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 }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

    app.use(session({
      secret: 'dadasdasdaxsax',
      resave: true,
      saveUninitialized: false
    }));

    app.use(passport.initialize());
    app.use(passport.session());

    // Express 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
        };
      }
    }));

    // Connect Flash
    app.use(flash());

    // Global Vars
    app.use(function (req, res, next) {
      res.locals.success_msg = req.flash('success_msg');
      res.locals.error_msg = req.flash('error_msg');
      res.locals.error = req.flash('error');
      res.locals.user = req.user || null;
      next();
    });

    app.use('/', indexPage);
    app.use('/product', ensureAuthenticated, productPage);
    app.use('/user', userPage);
    app.use('/category', ensureAuthenticated, categoryPage);
    app.use('/error', filenotfound);


    function ensureAuthenticated(req, res, next) {
      if (req.isAuthenticated()) {
        return next();
      } else {
        //req.flash('error_msg','You are not logged in');
        res.redirect('/');
      }
    }


    // 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 handler
    app.use(function (err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });


    //=========================CONNNNNNECTTTTTTEEEEEEDDDDDDDDDDDDDDDD======================//
  }
});



module.exports = app;