stormpath,express - 检查用户是否存在于路由中

时间:2016-08-18 22:17:33

标签: express router stormpath

使用此示例(https://stormpath.com/blog/build-nodejs-express-stormpath-app

我添加了一个路线和一个视图来显示一些用户帐户个人资料。

username: jsmith

http://localhost:3000/-jsmith  (note the -)

工作正常 - 即使没有用户登录。

如果用户不存在,则该应用程序只会挂起并且不会返回任何内容。

/-jsmithxxx

问:

  

如何测试用户是否存在,并返回查看“未找到用户”?

谢谢,Rob

app.get('/-:id', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  var id = req.params.id;
  console.log(id);
  next();
},
function (req, res) {
    var id = req.params.id;
req.app.get('stormpathApplication').getAccounts({ username: id }, (err, accounts) => {
  if (err) throw err;
    accounts.each((account, cb) => {
    console.log('Found matching account:', account);
    cb();
    console.log('username:' + account.username)
    res.render('user', {
    email: account.email,
    surname: account.surname,
    account:account  // this passes object, which can be used in view, no need to define email:account.email in server.js

  });
});
});
}
);

1 个答案:

答案 0 :(得分:0)

看起来这就是你想要的:

app.get('/-:id', function(req, res, next) {
  var id = req.params.id;
  var spApp = req.app.get('stormpathApplication');
  var acc;

  spApp.getAccounts({ username: id }, function(err, accounts) {
    if (err) {
      return res.send('An error occured. Please try again.');
    }

    accounts.each(function(account, cb) {
      acc = account;
      cb();
    }, function() {
      if (!acc) {
        return res.send('User not found.');
      }

      return res.render('user', {
        email: account.email,
        surname: account.surname,
        account:account
      });
    });
  });
});