gpt4 book ai didi

node.js - Nodejs 渲染 View 和模板 EJS

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:37 25 4
gpt4 key购买 nike

我有两个关于渲染 View 的问题,

为什么它不起作用?如果我将 res.render 放入 if(error) 中,它不会呈现新站点,但仍在当前页面上。第二个问题是,如果我在 ejs 模板 View 中,我输入 <%=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('/');
}
});

console.log(errors) 上是

[ { param: 'username', msg: 'Login is required', value: undefined }, { param: 'password', msg: 'Password is required', value: undefined } ]

最佳答案

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

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;

关于node.js - Nodejs 渲染 View 和模板 EJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45076872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com