初学node.js+mysql ,大佬们帮忙看看吧

router.post('/signin', function(req, res) {
  var username = req.body.username;
  var password = req.body.password;
  if(username&&password) {
    pool.getConnection(function(err, connection) {
      connection.query('select password from users where username="'+username+'"', function (err, result) {
          if(err){
              throw err;
          } else {
              if(result[0] === undefined) {
                  res.send('没有该用户。');
              } else {
                  console.log(result[0].password === req.body.password);//false
                  console.log(result[0].password);//123456
                  console.log(req.body.password);//123456
              }
          }
      })
    })
  }
});

这个地方是为什么?
console.log(result[0].password === req.body.password);//false

阅读 3.2k
5 个回答
新手上路,请多包涵

看看你是不是字符串和数字的区别。

你这一看就是===和==区别,类型不一样造成的

  1. JS里===和==是有区别的,===是严格相等
  2. 你的表结构,password字段是不是数值型的?

所以查询到的
result[0].password 是数字 123456

而外部提交进来的req.body.password是字符串型的,所以他们不严格相等

你打印一下 typeof result[0].passwordtypeof req.body.password 就知道了

新手上路,请多包涵

不需要处理事务的情况下,mysql可以直接使用pool.query()进行查询,不需要手动释放连接。
pool.getConnection()以后,需要使用connection.release()释放连接,不然pool会被用光

这样就可以了result[0].password + ''

console.log(result[0].password + '' === req.body.password);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题