【问题标题】:encryption in node js节点js中的加密
【发布时间】:2016-06-30 15:05:50
【问题描述】:

我尝试向 db 插入加密值,我可以加密无法在 db 中插入加密值的值。

app.post('/insert', function (req, res) {

    // var Fname=req.body.fname;
    // var Lname=req.body.pwd;

    var data = {
        Fname: req.body.fname,
        Lname: req.body.Lname
    };

    function hashP(getit, cb) {
        bcrypt.genSalt(15, function (err, salt) {
            if (err) {
                return console.log(err);
            }
            cb(salt);
            bcrypt.hash(getit, salt, function (err, gotit) {
                if (err) throw err;
                return this.cb(null, gotit);
            })
        })
    }

    hashP(data.Lname, function (err, gotit) {
        if (err) throw err;
        data.Lname = hash;
    })

    console.log(data.Lname);
    con.query("insert into test set ?", [data], function (err, rows) {
        if (err) throw err;
        res.send("Value has bee inserted");
    })
})

这是我的 html 表单页面:

<body>
<form action="http://localhost:8888/insert" method="POST" >
    <label>Name:</label><input type="text" name="fname"></br>
    <label>Lname:</label><input type="text" name="Lname"></br>
    <button type="submit">Submit</button>
</form>
</body>

【问题讨论】:

  • 错误是什么?
  • 我没有收到任何错误,来自 html 表单的数据直接插入到数据库中。但它不会转换为加密数据。当我签入终端时,我得到两个 Lname 值,一个是直接数据,另一个是加密数据。
  • 这看起来不对:data.Lname = hash; 因为hash 没有在任何地方定义。您的意思是改用gotit 吗?
  • 是的,你是对的,但是来自 html 的数据已被加密,但加密的值不会存储在 db 中,而不是存储 html 值,我认为我们必须更改查询。

标签: mysql node.js express


【解决方案1】:

似乎您的函数 hashP(getit,cb) 正在调用 cb 函数,不是吗?试试下面的

function hashP(getit, cb){
        bcrypt.genSalt(15, function (err, salt){
            if(err) {
                return cb(err, null);
            }
            bcrypt.hash(getit, salt, function (err, hash){
                if(err) {
                    return cb(err, null);
                }
                return cb(null, hash);
            })
        })
    }

另外,您需要在处理程序中调用它,如下所示:

app.post(...., function(req, res) {  

    var data = { ... }

    function hashP(data, cb){ ... }

    hashP(data.Lname, function (err, hash) {
      if (err) throw err;
      data.Lname = hash;
      // NOW, SAVE THE VALUE AT DB
      con.query("insert into test set ?", [data], function (err, rows) {
        if (err) throw err;
        res.send("Value has bee inserted");
    })
  }
}

这里的问题是异步执行,你用data调用con.query 之前 data是从hashP返回的

【讨论】:

  • 但是加密不会以这种方式发生,我只想在数据进入数据库之前对其进行加密。
猜你喜欢
  • 2019-09-09
  • 2021-09-30
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多