【问题标题】:Nodejs function evaluation explanationNodejs函数评估说明
【发布时间】:2014-02-07 19:03:23
【问题描述】:

我刚刚开始使用 Nodejs 和 Expressjs 来构建自定义应用程序。我在理解一段代码时遇到了一些麻烦。我不确定为什么这段代码有效。如果我能得到关于代码的解释或更好的方法来做同样的事情,我将不胜感激。

使用的成分

我正在使用 Nodejs V0.10.25 和 Express V3.4.8

情景

这段代码用于登录验证。用户名和密码采用 JSON 格式。一个 JS 函数接收从 POST 表单提交的用户名和密码作为参数,检查 JSON。如果用户名和密码在 JSON 中匹配,则该函数返回 true,否则返回 false。

下面是代码

JSON 文件

[{
    "username": "abc@example.com",
    "password": "abc",
    "name": "ABC"
}, {
    "username": "def@example.com",
    "password": "def",
    "name": "DEF"
}, {
    "username": "xyz@example.com",
    "password": "xyz",
    "name": "XYZ"
}]

app.js 中的 JSON 验证函数

/* Verify login from JSON */
function verifyLogin(username, password) {
    var file = 'json/login.json';

    fs.readFile(file, 'utf8', function (err, data) {
      if (err) {
        console.log('Error: ' + err);
        return;
      }

      data = JSON.parse(data);

      for (var i = 0; i < data.length; i++) {
          if(data[i].username === username && data[i].password === password) {
              return true;
          } else {
              return false;
          }
      }

    });
}

检查用户是否已登录 app.js 的功能

/* Check if session exists and user is logged in */
function checkAuth(req, res, next) {
  if (!req.session.user_id) {
    res.send('You are not authorized to view this page');
  } else {
    next();
  }
}

app.post() 获取 POST 值并在 app.js 中适当重定向

/* Login: Check POST email and password and redirect user */
app.post('/', function (req, res) {
  var post = req.body;
  if(post.email && post.password){
      if (verifyLogin) {
          /* Why is verifyLogin() working WITHOUT parameters */
          req.session.user_id = post.email;
          res.redirect('/inside');
      }
  } else {
      res.render('index', { 
        title: 'Logged in',
        error: 'The username and password you entered is incorrect'
    });
  }
});

现在的问题

为什么在 app.post 中的 if() 块中评估 verifyLogin() 而没有从 POST 传递用户名和密码作为参数?

我确定,我在这里做错了什么。如果有人能帮助我,那就太好了。

【问题讨论】:

    标签: javascript json node.js express


    【解决方案1】:

    verifyLogin 是一个 Function 对象。所有对象评估为真。

    即在条件上下文中使用非布尔类型时,将其转换为Boolean 对象。在 ECMA 中,它将使用抽象的ToBoolean 操作进行转换。

    Boolean(verifyLogin) //true
    
    !!verifyLogin //true
    

    此外,每次需要用户身份验证时,您都会读取 login.json 文件。在启动时读取它并缓存登录对象。您也不需要使用fs.readFile,因为可以使用require 导出.json 文件

    var login = require('json/login.json');
    

    更好的方法是使用verifyLogin 作为中间件: Array.prototype.any 将非常适合这一点,只要条件评估为真,就会返回

    function verifyLogin() {
      var login = require('json/login');
      return function (req, res, next) {
        var body = req.body,
        authenticated = login.any(function (user) {
          return body.email === user.username && body.password === user.password;
        });
        if(authenticated) {
          req.session.user_id = body.email;
          res.redirect('/inside');
        }
        else {
          res.render('index', { 
        title: 'Logged in',
        error: 'The username and password you entered is incorrect'
          });
        }
      }
    }
    

    【讨论】:

    • 非常感谢您的快速回复。那么,这是正确的方法还是有更好的方法?
    • 使用用户名和密码调用verifyLogin 是正确的方法。您可以通过使用verifyLogin 作为中间件来简化它
    • 酷。感谢所有的帮助。将其转换为中间件并检查。
    【解决方案2】:
    function verifyLogin(username, password) {
        var file = 'json/login.json';
        var isValidUser = false;
        try {
            var data = fs.readFileSync(file, 'utf8');
            data = JSON.parse(data);
            for (var i = 0; i < data.length; i++) {
              if(data[i].username === username && data[i].password === password) {
                  isValidUser = true;
              }
            }
            return isValidUser;
        } catch(e) {
            console.log('Error: ' + err);
            return false;
        }
    }
    

    此回调中的代码不会返回任何内容,但会返回 true。因为这是一个异步回调。检查syncReadFile函数!

    【讨论】:

    猜你喜欢
    • 2012-08-15
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2016-08-14
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多