получение ошибочных сообщений, не определенных в файле e js (при использовании fla sh в express) - PullRequest
0 голосов
/ 26 апреля 2020

Я пытаюсь распечатать, чтобы распечатать сообщение fla sh в файле e js. но выдает ошибку.

**ReferenceError: E:\nodeProject\views\login.ejs:10
    8| <body>
    9|     <h1>Login</h1>
 >> 10|     <% if(messages.error){%>
    11|         <%=messages.error%>
    12|         <%}%>
messages is not defined.**

Я сделал сервер. js в качестве основного js файла. Я установил необходимые модули, и проблема заключается в том, что он не распознает «messages.error» в моем файле e js. Вот некоторые утверждения в моем основном файле js (server. js):

const initializePassport=require('./passport-config');
const passport=require('passport');
const flash=require('express-flash');
const session=require('express-session');
const router=express.Router();

app.use(session({
    secret:process.env.SESSION_SECRET,
    resave :false,//if we want to resave the session variables if nothing has changed
    saveUninitialized:false//do u want to save an empty value if there is no value

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

router.route('/login').post(passport.authenticate('local',{
    successRedirect:'/',
    failureRedirect:'/login',
    failureFlash:true, 
}));

initializePassport(passport,email=>{
    MongoClient.connect(url,(err,db)=>{
        if(err) throw err;
        const dBase=db.db();
        dBase.collection('Users').find({email:email},(err,res)=>{
            if(err) throw err;
            console.log(res);
        })
        return res;
        db.close();
    });    
});

Это мой файл passport-config. js. Здесь я объявил сообщения, которые паспорт должен показывать как ошибку, если это происходит. Файл моего паспорта-конфигурации. js:

const localStrategy=require('passport-local').Strategy
const bcrypt=require('bcrypt');

function initialize(passport,getUserByEmail){
    const authenticateUser= async(email,password,done)=>{
        const user=getUserByEmail(email);
        if(user==null)
        {
            return done(null,false,{message:"No user with this email found"});                                                                    
        }
        try {
            if(await bcrypt.compare(password,user.password)){
                return done(null,user);
            }
            else{
                return done(null,false,{message:"Password does not match "});
            }

        } catch (error) {
            return done(error);          
        }
    }
    passport.use(new localStrategy({userName:'email'},authenticateUser));  
}
module.exports= initialize;

** Это файл e js, в котором я использую messages.error и получаю сообщение об ошибке, что сообщения не определены : **

<body>
    <h1>Login</h1>
    <% if(messages.error){%>
        <%=messages.error%>
        <%}%>



    <form action="/register" method="post">

    <div>
        <label for="name">Name</label>
        <input type="text" id="name" name="name" required>
    </div>
    <div>
        <label for="email">Email</label>
        <input type="email" id="email" name="email" required>
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" id="password" name="password" required>
    </div>
    <button type="submit">Login</button>
    </form>

    <a href="/register">Register</a>
</body>

Пожалуйста, посмотрите и скажите мне, что происходит не так. Я новичок, поэтому, пожалуйста, не возражайте, если мой способ спрашивать неуместен. Спасибо.

...