Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - How to render flash message in Node.JS?

I am trying to display flash message without render, just redirect. It can possible if it is how ?

const session = require('express-session');
const bodyParser = require('body-parser')
const urlencoded = bodyParser.urlencoded({extended:false})
const cookieParser = require('cookie-parser');

const flash = require('connect-flash');
app.use(cookieParser('secret'));
app.use(session({
  secret: 'keyboardSecrIncKey',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true, maxAge: 60000 }
}))

app.use(flash());

app.use('/test',urlencoded,(req,res,next)=>{
  if(req.body.name == ''){
    req.flash('info', 'Please Enter Your Name.');
    res.locals.message = req.flash();
    console.log(res.locals)
    res.redirect('back')
  }
  else{
    next()
  }
});

I am using handlebars view engine. And this is my test.handlebars file:

{{#if messages}}
 It is working
{{/if}}

But it won't display any text. If i use res.render('test', {...}) it is working. But while i click refresh button browser send me alert(confirm the re-form submission etc.)

question from:https://stackoverflow.com/questions/65600160/how-to-render-flash-message-in-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you redirect, you tell your user's browser to display some other page. It is in that page that you would display your flash message, not in the page using req.flash() to create a flash message.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...