节点:检查空值是否有效

时间:2018-06-04 12:34:40

标签: node.js

在以下函数中,我解析请求标头并获取currentUser的值。我记录了currentUser的值,并获得以下内容:

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

但是,currentUser的以下条件语句不会计算为null并执行后续行:

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 个答案:

答案 0 :(得分:2)

由于# Constructing a sparse tensor a bit more complicated for the sake of demo: i = torch.LongTensor([[0, 1, 5, 2]]) v = torch.FloatTensor([[1, 3, 0], [5, 7, 0], [9, 9, 9], [1,2,3]]) test1 = torch.sparse.FloatTensor(i, v) # note: if you directly have sparse `test1`, you can get `i` and `v`: # i, v = test1._indices(), test1._values() # Getting the slicing indices: idx = [1,2] # Preparing to slice `v` according to `idx`. # For that, we gather the list of indices `v_idx` such that i[v_idx[k]] == idx[k]: i_squeeze = i.squeeze() v_idx = [(i_squeeze == j).nonzero() for j in idx] # <- doesn't seem optimal... v_idx = torch.cat(v_idx, dim=1) # Slicing `v` accordingly: v_sliced = v[v_idx.squeeze()][:,idx] # Now defining your resulting sparse tensor. # I'm not sure what kind of indexing you want, so here are 2 possibilities: # 1) "Dense" indixing: test1x = torch.sparse.FloatTensor(torch.arange(v_idx.size(1)).long().unsqueeze(0), v_sliced) print(test1x) # torch.sparse.FloatTensor of size (3,2) with indices: # # 0 1 # [torch.LongTensor of size (1,2)] # and values: # # 7 0 # 2 3 # [torch.FloatTensor of size (2,2)] # 2) "Sparse" indixing using the original `idx`: test1x = torch.sparse.FloatTensor(autograd.Variable(torch.LongTensor(idx)).unsqueeze(0), v_sliced) # note: this indexing would fail if elements of `idx` were not in `i`. print(test1x) # torch.sparse.FloatTensor of size (3,2) with indices: # # 1 2 # [torch.LongTensor of size (1,2)] # and values: # # 7 0 # 2 3 # [torch.FloatTensor of size (2,2)] currentUser的结果,因此它可以是字符串或split。只有undefined字符串,它才能记录为null。混淆的原因是'null'null在使用'null'输出时无法区分。

  

但是currentUser的以下条件语句不会计算为null

仅当console.logcurrentUser字符串(或具有返回'null'字符串的自定义toString方法的任何对象)时,才可以执行此操作。

如果'null'currentUser'null'的评估结果为JSON.parse(currentUser),则可能出现null错误。

  

以及后续行执行

Cannot read property 'token' of null目前已注释,因此无论if (currentUser) {如何,都会执行这些内容。

问题可能应该事先通过currentUser来解决:

JSON.parse

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

答案 1 :(得分:0)

在空检查中

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
}

只需打印日志,但不会终止执行。以下代码仍将执行。