【问题标题】:getting parsed json value获取解析的 json 值
【发布时间】:2018-05-20 11:01:54
【问题描述】:

我正在尝试使用 bcrypt 检查保存在我的数据库中的哈希密码,但 json 响应当前返回如下:

[
    {
        "password": "$2a$10$8/o1McdQ24pL5MU7dkbhmewkjne83M2duPKp0cb6uowWvOPS"
    }
]

这会导致 bcrypt 比较出错,因为它正在比较整个响应,而不仅仅是其中的哈希值。我怎样才能在我的响应中获得哈希值?以下是我的代码:

app.get('/checkHash/:username/:pass', function(req, res) {
    console.log('below is the data');
    console.log(req.params);
    var pass = req.params.pass

        var createPromise = interact.getHash(req.params.username);
        //did promise
        createPromise.then(function(createResponse) {  
            //below checks to see if the password value matches the hash
            if(bcrypt.compareSync(pass, createResponse)) {
                //this means that the hashes are the same for user login
                res.json("yes");
            } else {
                //this means that the password hashes didn't match
                res.json("no");
         } 
        }).catch(function(err) {
        console.log(err);
    });
});

【问题讨论】:

    标签: json node.js parsing


    【解决方案1】:

    您的响应显然是一个对象数组。如果您只想比较数组的第一个结果,则必须将索引传递给数组。

    app.get('/checkHash/:username/:pass', function(req, res) {
        console.log('below is the data');
        console.log(req.params);
        var pass = req.params.pass
    
            var createPromise = interact.getHash(req.params.username);
            //did promise
            createPromise.then(function(createResponse) {  
                //below checks to see if the password value matches the hash
                if(bcrypt.compareSync(pass, createResponse[0].password)) {
                    //this means that the hashes are the same for user login
                    res.json("yes");
                } else {
                    //this means that the password hashes didn't match
                    res.json("no");
             } 
            }).catch(function(err) {
            console.log(err);
        });
    });
    

    【讨论】:

    • 这仍然返回整个 json 对象作为密码,我正在寻找密码的字符串值:"$2a$10$8/o1McdQ24pL5MU7dkbhmewkjne83M2duPKp0cb6uowWvOPS"
    • 那么你只需要访问对象的属性。使用createResponse[0].passwordcreateResponse[0]['password']。更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    相关资源
    最近更新 更多