How to access passport req.user variable on client side javascript?

I have Passport authentication installed in my simple express application and it works fine and I have req.user displaying on my index page, for example:

<% if (!isAuthenticated) { %>
    <a id="signIn" href="/login">Sign In</a>
<% } else { %>
    <h3 id="welcomeMsg"><%=user.id%></h3>
    <h2 id="userBalance"><%=user.balance%></h2>
    <a href="/logout">Log Out</a>
<% } %>

In index.js:

app.get('/', function(req, res){
  res.render('index', {
     isAuthenticated: req.isAuthenticated(),
     user: req.user
});

});

What I want to do is confirm the name of the user who signed up in the client side js file in my shared directory. What will be the easiest and easiest way to make this variable available in this file?

thank

+4
source share
1 answer

passport.js cookie, , json:

app.get('/api/user_data', function(req, res) {

            if (req.user === undefined) {
                // The user is not logged in
                res.json({});
            } else {
                res.json({
                    username: req.user
                });
            }
        });

javascript , jQuery.getJSON() , GET json-.

jQuery.getJSON():

$.getJSON("api/user_data", function(data) {
    // Make sure the data contains the username as expected before using it
    if (data.hasOwnProperty('username')) {
        console.log('Usrename: ' + data.username);
    }
});
+9

All Articles