2017-11-25 156 views
1

我一直跟着教程我節點應用程序來實現認證:https://scotch.io/tutorials/easy-node-authentication-setup-and-local未定義的消息變量的NodeJS

我有被我發現了在運行應用程序時,這個錯誤的問題:(我的代碼是exacltly如何應根據上述網站)。

enter image description here

我試圖尋找一個答案,但最好我能得到的是增加這個功能到我的服務器代碼:

app.use(function(req, res, next){ 
    res.locals.message = req.flash(); 
    next(); 
}); 

這會將然而沒有任何錯誤的應用程序,該消息不似乎顯示在我的前端。不完全確定爲什麼,但我只能通過這個項目得到這個問題,我可以在我的其他項目中沒有任何問題的情況下實現消息。

我添加以下,但我的繼承人GitHub的鏈接我的代碼位:

routes.js

app.post('/signup', passport.authenticate('local-signup', { 
    successRedirect : '/dashboard', 
    failureRedirect : '/#contact', 
    failureFlash : true 
})); 

passport.js

if (user) { 
    return done(null, false, req.flash('signupMessage', 'Email already in use!')); 
} 

指數。 ejs

<% if (message.length > 0) { %> 
    <div class="alert alert-danger"><%= message %></div> 
<% } %> 

Github的項目:https://github.coventry.ac.uk/salmanfazal01/304CEM-Back-End

回答

1

從錯誤中,我認爲你沒有正確傳遞變量messageejs視圖。

所以,你有2個解決方案

1-在您routes.js文件,你需要傳遞信息,而渲染index認爲,這是你如何以下的例子就完成了。

所以更改

//GET homepage 
app.get('/', function(req, res) { 
    res.render('index'); 
}); 

//GET homepage 
app.get('/', function(req, res) { 
    res.render('index' , {message: <your data> }); 
}); 


2 - 使用res.localsres.flash這是你找到了解決辦法,但你實際上並沒有傳遞任何值req.flash()

所以將這段代碼

app.use(function(req, res, next){ 
    res.locals.message = req.flash(); 
    next(); 
}); 

app.use(function(req, res, next){ 
    req.flash("info" , "first message"); //here you add message under type info 
    req.flash("info" , "second message"); // here you add another message under type info 

    next(); 
}); 

,並在您route.js

app.get('/', function(req, res) { 
     res.render('index' , {message : req.flash("info")}); //set message from req.flash type info 
    }); 

    //or 

    app.get('/', function(req, res) { 
     res.locals.message = req.flash("info"); //set locals.message from req.flash type info 
     res.render('index'); 
    }); 
+0

你是一個傳奇隊友!我花了最後幾個小時試圖修復它,結果變得如此輕微:/ 嘗試了你的第一個解決方案,它工作。基本上,我的註冊/表單位於我的索引頁面中,並且我將它們分開渲染,並在其中傳遞消息而不是主要的主頁面。乾杯! –

+0

很高興幫助:) –