LoginSignup
1
0

connect-flashのメッセージが消える

Posted at

Express3系でFlashメッセージを表示する為、connect-flashというパッケージを追加して、(勝手に)罠にハマったので共有しておきます。

サンプルコードを見ながら、下記のようなコードを書いて動作チェックしました。

app.js
app.get('/flash', function(req, res){
  req.flash('info', 'Flash is back!')
  res.redirect('/');
});

app.get('/', function(req, res){
  console.log(req.flash('info'));  // デバッグ用にメッセージを仕込んだ
  res.render('index', { messages: req.flash('info') });
});
index.ejs
<% if (messages){ %>
  <p><%= messages %></p>
<% } %>

問題

app.jsのconsole.logのではコンソールにメッセージが表示されるのですが、Viewでは表示されません。

原因

req.flash('info') を参照すると中身が消去されるようです。
今回、デバッグ用のconsole.logが最初に参照した為、Viewに渡す時には中身が空になっていました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0