該快遞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;
好還給我HTML頁面,但問題是我怎麼能顯示錯誤?因爲<%if(errors.length> 0){%>
這可能是因爲您沒有正確配置服務器。請在您的問題中包含這些信息。 – sidhuko
我補充一下,請看看你是否可以 –