Unable to display flash message in view with ejs template - node.js

I am a newbie in NodeJS. I have a problem that I am unable to show flash message in my view.
Here is my Controller,
index : function(req, res){
res.locals.flash = _.clone(req.session.flash);
res.locals.layout = false;
res.view('login');
},
login : function(req, res){
....
if(!admin){
req.session.flash = {
err : 'User is not found.' // My flash message
}
res.locals.layout = false;
res.redirect('login');
return;
}
.....
}
Here is my view,
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
<% JSON.stringify(flash.err) %>
</div>
<% } %>
When login is false, it show only an empty alert box.
And I have a second problem. When I refresh page, The alert box isn't disappeared.
Could someone help me please.
Thanks a lot.

The alert box keeps on appearing because the req.session.flash object persists the session, so you need to null that out once it's used, or you can just simply use req.flash(), which does that for you. So change your index method to something like this:
index: function(req, res) {
// req.flash() returns the contents of req.session.flash and flushes it
// so it doesn't appear on next page load. No need to clone.
res.locals.flash = req.flash();
res.locals.layout = false;
res.view('login');
},
Now, onto the second problem. The error messages aren't appearing because you aren't using the proper EJS syntax to output escaped values into the view. All you need to do is change your code to this:
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
// Change <% to <%=
<%= flash.err %>
</div>
<% } %>
No need to JSON.stringify, unless you like the quotes. Notice that I changed the <% to <%=, which in EJS means "escape this and output it". It's not template HTML or anything like that, so it's okay to escape it anyway.

Related

How do i make the ejs variable work that i send from nodejs?

I am tring to get a variable that i send from nodejs to ejs to work. But for some reason it wont, i cant figure out why.
This is the index.js:
var newOne = "Yes"
router.get('/main', ensureAuthenticated, (req, res) =>
res.render('main', {
user: req.user,
newOneInView : newOne
})
)
And this is in the main.ejs file:
<%if (newOneInView == "Yes") { %>
document.getElementById("avatar").src = "/static/images/Apocaliptic1.png";
<% } %>
So what i am trying to achieve is that variable will be seen from the nodejs at the main.ejs page but some reason it wont change the image SRC. What am i doing wrong here?
In your template you need to make sure that you place the code for changing the src attribute in a script that is placed after the element (alternatively you can use a listener for the content to be loaded), e.g:
<body>
<img id="avatar" src="/some-other-path"/>
<script>
<% if (newOneInView === "Yes") { %>
document.getElementById("avatar").src = "/static/images/Apocaliptic1.png";
<% } %>
</script>
</body>

Use console.log in EJS

Is it possible to use console.log in a node / ejs template? It doesn't seem to do anything when I try, even something as simple as:
<% console.log('test') %>
I've also tried:
<%= console.log('test') %>
Nothing shows up in the console.
I think you are expecting it to show in the developer console. It will not show up there.
console.log() in EJS file will show the log in the terminal where the server is running.
This worked perfectly
<% console.log('heheeh', JSON.stringify(doc, null, '\t')) %>
console.log() is working fine, but its log does not display in dev tools.
So, check your terminal first:
<% console.log("test") %>
It's perfect.
console.log(test) in ejs file will show the log in the terminal
And if you want to see test object or value in browser than try
<%= test %>
This will show objects as string
I know this is a really old thread, but I just had this issue and this is what I ended up doing:
<% var data = JSON.stringify(htmlWebpackPlugin) %>
<script>
console.log(<%= data %>)
</script>
It doesn't look pretty, but it works
Code
Output
<% console.log(posts) %>
NB: Make sure you define your variable in any other file you have eg app.js file...
let posts = [];
app.get("/", (req, res) => {
res.render("home", {
posts: posts
});
});
OUTPUT
Click me
first, Your home route inside your index.js/server.js/app.js, render a variable you want console log in another ejs file; in the code below, nposts is a variable or an array;
app.get("/",function(req,res){
res.render("home", {posts: nposts});
then in your ejs file, in this example in the home.ejs console.log in the <% %> tags
<% console.log(posts); %>
send from serve-side
let item = [arr1, arr2, arr3]
res.send("index", { item })
in client-side
example
use in script
console.log('<%- item %'>
arr1,arr2,arr3
console.log('<%- JSON.stringify( item ) '%>
["arr1","arr2","arr3"] //text
var newArray = JSON.parse('<%- JSON.stringify( item )%>')
console.log(newArray )
<% { %>
<script>console.log('hello')</script>
<% } %>
this code is work well.
create { } by <% %> from ejs.
We can add javascript code inside { }.
The simple answer would be:
If you are in your home route and you want to test any condition you would have to use ejs tags. inside the tags drop your normal console.log.
<% console.log(test) %>

Conditional operators in ejs

This might sound really easy. There is a very similar
answer but somehow my code is behaving abruptly and driving me crazy. I have spent last 4-5 hours on this. Any help would be great.
I am building a Socket.IO chat app using Node + Express + Passport. I want to compare the userId of the current user with that of other users connected. I want to show him all users except himself to chat with in Socket.IO.
Read comments on code for clarity :
users.js
app.get('/users', function (req, res) {
var connectedUsers = require('../app').chatUsers; // => This is an array of all logged in user and I am getting this all correctly.
if (req.isAuthenticated()) {
res.render('users', {
currentUser: req.user,
users: connectedUsers,
title: 'OnLineUsers'
});
}
});
users.ejs
<h3>CurrentUser : <%- currentUser.id %></h3> // => This Prints like **abcdefg**
<% for(var i = 0;i < users.length ; i++){ %>
<h3>UserID: <%- users[i].id %></h3> // => This also prints the same **abcdefg** if only one user is connected.
<% if( currentUser.id !== users[i].id){ %> // => But this Conditional Operator does not works and show the current user himself.
<ul>
<li>
<h3> <%= users[i].name %></h3>
<a href="/socket" id="chatRoomUrl">
<button type="submit" class="btn-success">Chat</button>
</a>
</li>
</ul>
<% } %>
<% } %>
Thanks in advance. If there is any silly mistake on my part, please excuse me for wasting your time.
Your code is fine. Maybe there is space in two property. Try :
currentUser.id.trim() !== users[i].id.trim()
Change your following line, notice the change:
<h3> <%= users[i].name %></h3>
to this:
<h3> <%- users[i].name %></h3>

Sails.js flash message for user registration

I am following Sail.js tutorial from http://irlnathan.github.io/sailscasts/blog/2013/08/27/building-a-sails-application-ep4-handling-validation-errors-with-a-flash-message/
However I ran into a small problem. In the tutorial the author uses registration files inside his user folder and assigns routes in the user controller. He then sends validation errors using flash to the user.
However in my project, the registration files lies in the root folder and I assign the routes from the routes.js file like so
module.exports.routes = {
'/': {
view: 'index'
},
'/register': {
view: 'register'
}
};
Now the problem is to using flash to show users the validation errors while registration. I have used the following in the user controller (create) and it doesn't seem to work
if (err){
err.success = 0;
console.log(err);
req.session.flash = {
err: err
}
req.flash('error', req.session.flash);
return res.redirect('/register');
}
Any suggestions?
Sails.js version < 0.10.x based on his other thread output here
EDIT: See the Sails documentation here for more information - basically, since you're using static routing, no policies are applied before rendering the view, hence the flash policy isn't working. I'd recommend adding a register action in your UserController and just calling res.view() from there. There's also a StackOverflow post that discusses this, if you want more information.
I do have an alternative I developed for my own project that you can try out (also requires non-static routing).
In your api/policies folder, create a policy flash.js:
// flash.js policy
module.exports = function(req, res, next) {
res.locals.messages = { success: [], error: [], warning: [] };
if(!req.session.messages) {
req.session.messages = { success: [], error: [], warning: [] };
return next();
}
res.locals.messages = _.clone(req.session.messages);
// Clear flash
req.session.messages = { success: [], error: [], warning: [] };
return next();
};
This policy allows for three different flash types: success, warning, and error. It'll create an empty dictionary for each session and clear it on page loads.
I created a service FlashService.js in api/services to more easily flash messages:
// FlashService.js
module.exports = {
success: function(req, message) {
req.session.messages['success'].push(message);
},
warning: function(req, message) {
req.session.messages['warning'].push(message);
},
error: function(req, message) {
req.session.messages['error'].push(message);
}
}
Then, in your config/policies.js config file, make sure to assign the flash policy to the controller actions that you want to use flash with:
// config/policies.js
module.exports.policies = {
'*': [true, 'flash'],
'UserController': {
'register': ['flash'],
// any future actions that want flash
},
'AnotherController': {
'someAction': ['flash', 'somePolicy'],
}
}
To flash a message in your register action, just use FlashService.success(req, message). Alternatively, you can use FlashService.error and FlashService.warning, depending on how your UI styling works and how much you want to differentiate your flash messages.
In your view, you can put something like this:
<% if (messages && messages['error'].length > 0) { %>
<div class="alert alert-danger">
<% messages['error'].forEach(function(message) { %>
<%= message %>
<br>
<% }); %>
</div>
<br>
<% } %>
<% if (messages && messages['warning'].length > 0) { %>
<div class="alert alert-warning">
<% messages['warning'].forEach(function(message) { %>
<%= message %>
<br>
<% }); %>
</div>
<br>
<% } %>
<% if (messages && messages['success'].length > 0) { %>
<div class="alert alert-success">
<% messages['success'].forEach(function(message) { %>
<%= message %>
<br>
<% }); %>
</div>
<br>
<% } %>
Of course, you'll have to change the div classes to whatever classes are relevant to your UI.
In a normal mvc like rails or cakephp handling flash is something like this: $this->Flash->error('An Error Occurred Message'); then displayed it in an element.
In sails it should be simple as that.
In Controller: req.flash('error', 'An Error Occurred Message');
In View Partial: flash.ejs
<% if (req.session.flash) { %>
<% if (req.session.flash.success) { %>
<div data-alert class="alert-box success radius">
<%= req.flash('success') %>
×
</div>
<% } %>
<% if (req.session.flash.warning) { %>
<div data-alert class="alert-box warning radius">
<%= req.flash('warning') %>
×
</div>
<% } %>
<% if (req.session.flash.error) { %>
<div data-alert class="alert-box alert round">
<%= req.flash('error') %>
×
</div>
<% } %>
<% } %>
On Layout:
<%- partial('partials/flash') %>
Handling Error Message per field should be part in a Validation and Html Helper. (Like for example: https://gist.github.com/mikermcneil/8366092)
You can add this export:
module.exports = function flash(req, res, next) {
if (!req.session.flash) {
req.session.flash = {};
req.session.flash['success'] = [];
req.session.flash['warning'] = [];
}
next();
};
and then in the view:
<% if (req.session.flash['success'].length > 0) { %>
<div class="alert alert-success">
<%= req.session.flash['success'].pop() %>
</div>
<% } %>
<% if (req.session.flash['warning'].length > 0) { %>
<div class="alert alert-warning">
<%= req.session.flash['warning'].pop() %>
</div>
<% } %>
You can create messages in the controller like this:
req.session.flash['success'].push('Updated successfully');

express + ejs login widget

I am trying to make easy widget for buttons login/logout.
laout.ejs
<% include ../shared/login_logout %>
login_logout.ejs
<% if ( !common.IsDefined(membershipHelper.GetCurrentUser(request , response)) ) { %>
<li class="pull-right">Login</li>
<% } else { %>
<li class="pull-right">Log Out</li>
<% } %>
membershipHelper.GetCurrentUser - this method checks request session for user_id and if it finds it returns user if it is found in db(mongoDB) else it returns null. As user is returned in callback function of User.findById ejs file receives "undefined" always. I thought to put this GetCurrentUser in the middleware but it look like I can't set null or undefined to locals variable
What can be solution for this problem?

Resources