2017-07-13 119 views
1

我有兩個關於渲染視圖的問題,Nodejs渲染視圖和模板EJS

爲什麼它不起作用?如果我把res.render放入if(error),它不會渲染新的網站,但仍然在當前頁面上。 而第二個問題是,如果我在EJS模板視圖,我把<%=錯誤%>來顯示錯誤,並且其它的工作原理,示出了錯誤文件未找到

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

上的console.log(錯誤)是

[{PARAM: '用戶名',消息: '登錄需要',值:未定義}, {PARAM: '密碼', 消息: '需要密碼', 值:未定義}]

回答

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; 
+0

好還給我HTML頁面,但問題是我怎麼能顯示錯誤?因爲<%if(errors.length> 0){%>

<%= errors %>
<% } %>重定向到頁面文件未找到 –

+0

這可能是因爲您沒有正確配置服務器。請在您的問題中包含這些信息。 – sidhuko

+0

我補充一下,請看看你是否可以 –