Reputation: 1676
I am trying to flash a message of a JSON Parsed response from request module that sends POST request to a third party api.
The below code shows how I handle the response (clientServerOptions is the request):
request(clientServerOptions, function (error, response) {
console.log(error,response.body);
var jsonResponse=JSON.parse(response.body);
if(jsonResponse.ok){
}else{
req.flash('errMsg',jsonResponse.message);
console.log(req.flash('errMsg')); // This line prints the message
}
console.log(req.flash('errMsg')); // this line doesn't, it's empty
console.log('=======After redirect======');
res.redirect('/entities');
});
In the if else condition, console.log shows the req.flash('errMsg'), but once it's outside the condition scope. req.flash('errMsg') is empty.
Answer: only call req.flash('xxx') at the place where you really use it, if you call it somewhere else before the actual use, it clears the value it stores
Upvotes: 0
Views: 482
Reputation: 2134
Flash messages are for one time use only, those get cleared once used.
Thus when you do req.flash('errMsg')
in if else
, it displays the message on console and then clears it. That's why on line after if/else
you get the empty message displayed.
Upvotes: 1