mjanisz1
mjanisz1

Reputation: 1516

Express doesn't pass object to the view

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?

Upvotes: 1

Views: 1956

Answers (1)

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 <% user %> 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:

<p>{{ user }}</p>

call:

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

result:

<p>{"name": "monkey"}</p>

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

index:

<script> var user = {{ user }}; </script>

call:

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

result:

<script> var user = {"name": "monkey"}; </script>

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

Upvotes: 3

Related Questions