代码之家  ›  专栏  ›  技术社区  ›  koque

节点:检查空值无效

  •  1
  • koque  · 技术社区  · 7 年前

    在下面的函数中,我解析请求头并获取currentuser的值。我记录currentuser的值并得到以下结果:

    console.log('currentUser', currentUser)
    currentUser null
    

    但currentuser的以下条件语句的计算结果不为空,将执行后续行:

    if (!currentUser) {
        console.log('\n user not logged in');
        res.status(401).json('User not logged in');
    }
    

    错误:

    TypeError: Cannot read property 'token' of null
    at exports.authenticate (sandbox2\nghd09\backend\app\controllers\user.server.controller.js:47:40)
    at Layer.handle [as handle_request] (sandbox2\nghd09\node_modules\express\lib\router\layer.js:95:5)
    

    整个功能:

    exports.authenticate = function (req, res, next) {
        var headerExists = req.headers.authorization;
        console.log('authenticate called', headerExists)
        var currentUser = req.headers.authorization.split(' ')[1];
        console.log('currentUser', currentUser)
    
        if (!currentUser) {
            console.log('\n user not logged in');
            res.status(401).json('User not logged in');
        }
    
        // if (currentUser) {
        var token = JSON.parse(currentUser).token;
        console.log('\ntoken', token)
        jwt.verify(token, config.sessionSecret, function (err, decoded) {
            if (err) {
                console.log(err);
                res.status(401).json('Unauthorized');
            } else {
                req.user = decoded.username;
                req.password = decoded.password;
                next();
            }
        })
        // }
    }
    

    我遵循了stackoverflow的一些建议,但是没有成功。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Estus Flask    7 年前

    自从 currentUser 是由于 split ,它可以是字符串,也可以是 undefined . 它可以记录为 null 如果是的话 'null' 字符串。混乱来自于这样一个事实 无效的 “空” 与输出时无法区分 console.log .

    但是currentuser的以下条件语句的计算结果不是空的

    只有当 当前用户 “空” 字符串(或任何具有自定义 toString 返回的方法 “空” 字符串)。

    如果 当前用户 “空” , JSON.parse(currentUser) 评估为 无效的 这样 Cannot read property 'token' of null 可能出错。

    并执行后续行

    if (currentUser) { 当前已被注释,因此无论 当前用户 .

    可能的问题应该通过执行 JSON.parse 事先:

    var currentUser = req.headers.authorization.split(' ')[1];
    if (currentUser !== undefined) {
       currentUser = JSON.parse(currentUser);
    }
    
    if (!currentUser) {
        console.log('\n user not logged in');
        res.status(401).json('User not logged in');
    }
    

    授权头中存在null这一事实是另一个可能需要额外解决的问题。

        2
  •  0
  •   John    7 年前

    在空检查内

    if (!currentUser) {
      console.log('\n user not logged in');
      res.status(401).json('User not logged in');
      //return next();   // should return next here to stop current function
    }
    

    只打印日志,但不终止执行。下面的代码仍将被执行。

    推荐文章