如何在客户端javascript中访问Passport的req.user变量?

时间:2022-06-22 03:21:03

I have Passport authentication set up on my simple Express app and it works fine, and I have it displaying req.user on my index page like this:

我在我的简单Express应用程序上设置了Passport身份验证,它工作正常,我在索引页面上显示req.user,如下所示:

<% 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 username of who's signed in, in a client side js file in my public directory. What would be the simplest and most straightforward way to make that variable available in that file?

我想要做的是在我的公共目录中的客户端js文件中确认谁登录的用户名。在该文件中使该变量可用的最简单,最直接的方法是什么?

Thank you

1 个解决方案

#1


11  

Since the passport.js mantains a session by using a cookie, you can add a simple route in your application that provides the current logged user data in json format:

由于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
                });
            }
        });

and access it with your client side javascript using jQuery.getJSON() or any other method that can GET request a json content.

并使用jQuery.getJSON()或任何其他可以请求json内容的方法,使用客户端javascript访问它。

Example with jQuery.getJSON():

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);
    }
});

#1


11  

Since the passport.js mantains a session by using a cookie, you can add a simple route in your application that provides the current logged user data in json format:

由于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
                });
            }
        });

and access it with your client side javascript using jQuery.getJSON() or any other method that can GET request a json content.

并使用jQuery.getJSON()或任何其他可以请求json内容的方法,使用客户端javascript访问它。

Example with jQuery.getJSON():

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);
    }
});