Re: [nodejs] How to dynamically update products on main root (ecommerce) with nodejs+express+jade?

184 views
Skip to first unread message

Ryan Schmidt

unread,
Mar 8, 2013, 3:26:10 AM3/8/13
to nod...@googlegroups.com

On Mar 7, 2013, at 21:07, jatin...@gmail.com wrote:

> So, here's my main home page (/) route - in the router.js file:
>
> app.get('/', function(req,res){
> // check if the user's credentials are saved in a cookie //
> if (req.cookies.user == undefined || req.cookies.pass == undefined){
> res.render('index');
> }
> else {
> res.render('index', {username: req.cookies.user});
> }
> });
>
> However, how do I dynamically render data on the home/main/index page such as different list of events.

> One way I am thinking I can do this is implement some logic in the app.get route before I render index like so:
> app.get('/', function(req,res){
> // check if the user's credentials are saved in a cookie //
> if (req.cookies.user == undefined || req.cookies.pass == undefined){
> eventArray = getAllEvents(list, fn);
> ....callback logic...
> if (!events){
> res.render('index');
> }
> else {
> res.render('index', {event 1 data, event 2 data, event 3 data...});
> }
> }
> else {
> res.render('index', {username: req.cookies.user});
> }
> });
> But this looks like a bad way to code this - no?

That seems like a reasonable solution. What do you think it's a bad way to code?

jatin...@gmail.com

unread,
Mar 8, 2013, 9:38:44 AM3/8/13
to nod...@googlegroups.com
Thank you.
I was hoping there would be another way to deal with this - there's going to be so much processing/logic that I need to put in this else...
because for e.g.
Some events are featured events so they belong in appropriate parts/sections of the home page while others get smaller real estate on the home page and so on.

Thanks,
JP

Paul Selden

unread,
Mar 9, 2013, 11:32:29 AM3/9/13
to nod...@googlegroups.com
One thing I would do is add a middleware for detecting whether a user is authenticated, and serve a different route based on that.

function requireAuthentication(req, res, next){
   if (req.cookies.user == undefined || req.cookies.pass == undefined){
      next('route'); // this tells express to skip the current route
   } else {
      next();
   }
}

app.get('/', requireAuthentication, function loggedIn(req, res, next){
    // you can assume your user is logged in here.
    res.render('indexLoggedIn', { username: req.cookies.user });
});

app.get('/', function(req, res, next){
   // you can assume your user is logged out here because routes are executed in order -- or add another middleware to verify it so you don't have to care about order
  // fetchEvents
  res.render('index', { events: events });
});

jatin...@gmail.com

unread,
Mar 9, 2013, 4:49:28 PM3/9/13
to nod...@googlegroups.com
Thanks Paul - actually that solves one of the other issues.



Thanks,
JP
Reply all
Reply to author
Forward
0 new messages