Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Express doesn't pass object to the view

Express doesn't pass object to the view

Problem

Im trying to Send a user Object from passport to the browser, but all I get is window.user undefined in the console.

In the route I've checked the object with console.log("USER:"+JSON.stringify(req.user, null, 4))

and I get the proper output:

USER :{
    "emails": [
        {}
    ],
    "nick": "nickname",
    "identifier": "76561197990749921",
    "points": 140
}

While trying to send it with res.render('index', {user: req.user}); I cant retrieve it from the window object. But when i send some property for example res.render('index', {user: req.user.points}); it is attached to window.user as its supposed to... On the other hand while trying to send req.user.nick its also not attached to window. What may be the problem?

Problem courtesy of: mjanisz1

Solution

render does not preserve objects. The object you pass the .render function gets used as string-macros for your template, so if your index template has a {{ user }} or in it (syntax depending on the templating engine you picked), then it'll write the string that your user content coerces to into your file.

index:

{{ user }}

call:

res.render('index', {user: {"name": "monkey"}});

result:

{"name": "monkey"}

And that's text, not a JavaScript object. Of course we could make sure the string goes into a script block:

index:

call:

res.render('index', {user: {"name": "monkey"}});

result:

And now we can suddenly use it in the rest of our on-page JavaScript.

Solution courtesy of: Mike 'Pomax' Kamermans

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Express doesn't pass object to the view

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×