首页 > 解决方案 > 如何在 app.get 之外使用 req.user?

问题描述

我一直在开发一个类似于https://rustbet.com的网络应用程序。这是一些代码:

passport.serializeUser(function(user, done) {
  done(null, JSON.stringify(user));
});
passport.deserializeUser(function(obj, done) {
  done(null, JSON.parse(obj));
});

我正在本地序列化用户。

passport.use(new SteamStrategy({
  returnURL: 'http://localhost:80/auth/steam/return',
  realm: 'http://localhost:80/',
  apiKey: '------------------'
  },
  function(identifier, profile, done) {
      process.nextTick(function () {
      profile.identifier = identifier;
      return done(null, profile);
      });
  }
));

使用蒸汽护照策略

app.use(session({
    secret: '---------',
    name: 'user_session',
    resave: true,
    saveUninitialized: true}));

会话

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

这就是我目前使用数据的方式

如何在 http 请求/EJS 模板之外使用 req.user 对象?例如在我需要的 socket.io 应用程序中。我浏览了 stackoverflow 并找到了许多答案,但没有一个是最近的。此外,我对我最有可能错过的任何最佳实践持开放态度。

标签: javascriptnode.jssocket.io

解决方案


推荐阅读