Я пытаюсь преобразовать несколько кусков мопса в EJS, но он не работает, и это также приводит к сбою моей страницы.
, пытаюсь показать мои «сообщения об ошибках» для моей «формы регистрации», но не могучтобы преобразовать приведенного ниже мопса в EJS:
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
Я также пытаюсь преобразовать приведенного ниже мопса в EJS для моих «сообщений» (используя flash), чтобы сказать «вы вошли в систему»:
!= messages()
Также можно сказать, что класс «Активен», например, когда я на странице «Регистрация» или «Домашняя страница», но снова пытаюсь преобразовать мопса в EJS:
li(class=(title == 'Signup' ? 'active' : ''))
Мой класс App.js
// define dependencies
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 LocalStrategy = require('passport-local').Strategy;
var ejs = require('ejs');
var expressValidator = require('express-validator');
var multer = require('multer');
var upload = multer({dest: './uploads'});
var flash = require('connect-flash');
var bcrypt = require('bcryptjs');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
// const PORT = 3000; // you can change this if this port number is not available
const port = process.env.PORT || 3000;
//requiring the routes
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');
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')));
// Handle Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//passport middleware
app.use(passport.initialize());
app.use(passport.session());
//Express Validator middleware
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
};
}
}));
//flash middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('*', function(req, res, next){
res.locals.user = req.user || null;
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);
});
//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 erro 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: {}
});
});
app.listen(port, () =>{
console.log(`Server is up on port ${port}`);
});
module.exports = app;
User.js
var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({dest: './uploads'});
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
// GET home page.
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
router.get('/signup', function (req, res, next) {
res.render('signup', {title: 'Signup'});
});
router.get('/signin', function (req, res, next) {
res.render('signin', {title: 'Signup'});
});
//passport control for signing in.
router.post('/signin',
passport.authenticate('local',{failureRedirect:'/users/signin', failureFlash: 'Invalid username or password'}),
function(req, res){
req.flash('success', 'You are now logged in');
res.redirect('/');
});
passport.serializeUser(function(user, done){
done(null, user.id);
});
passport.deserializeUser(function(id, done){
User.getUserById(id, function(err, user){
done(err, user);
});
});
//locat strategy to control correct usernames + passwords
passport.use(new LocalStrategy(function(username, password, done){
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) return done(err);
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Invalid Password'});
}
});
});
}));
router.post('/signup', upload.single('profileimage'), function (req, res, next) {
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 {
console.log('No File Uploaded...');
var profileimage = 'noimage.jpg';
}
// Form Validator
req.checkBody('name', 'Name field is require').notEmpty();
req.checkBody('email', 'Email field is require').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('username', 'Username field is require').notEmpty();
req.checkBody('password', 'Password field is require').notEmpty();
req.checkBody('password2', 'Password do not match').equals(req.body.password);
//check Errors
//error handing for signing + registering
var errors = req.validationErrors();
if(errors){
res.render('signup', {
errors: errors
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileimage: profileimage
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success', 'You are now registered and can signin');
res.location('/');
res.redirect('signin');
}
});
router.get('/logout', function(req, res){
req.logout();
req.flash('success', 'You are now logged out');
res.redirect('/users/signin');
});
module.exports = router;
Репозиторий Git: https://github.com/johnnymunster/WebDev-Project URL Heroku: https://glacial -castle-40173.herokuapp.com/
Заранее спасибо Джонни