Вопрос

This is essentially a continuation of the question here: Nodejs Passport display username.

app.get('/hello', function(req, res) {
    res.render('index.jade', { name: req.user.username });
});

So users log in via PassportJS, and goes to index.jade, which contains #{name} in the body, which will be replaced by the value of req.user.username.

Question: Is it possible to use the value of req.user.username in index.jade's JavaScript? I tried assigning its value to a variable but it doesn't work.

I have been using the trick of having a hidden input with #{name} as value:

input(type='hidden', id='variableName', value='#{name}')

Then JavaScript can access this value using:

$("#variableName").val()

This works. But does it have any potential downside like security issues? What is the right way to do this?

Это было полезно?

Решение

You have a few options. One of them is what you did and put the value inside you html. You can also solve it by doing:

script
   window.name = #{name};

This will create an inline script that sets the variable. The other option you have is using ajax. That means you probably need to make an extra route to reply to that request.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top