我无法从sql查询中读取值

时间:2019-12-28 12:44:13

标签: javascript mysql node.js

我向数据库发送查询,并且在TextRow对象中得到响应,但我无法读取值始终是未定义的。我想从数据库中读取分配给电子邮件的密码,以便用户可以登录。所有控制台日志都返回未定义

    const db = require('../db/mysql');
    router.post("/login", (req, res, next)=>{
    let email = req.body.email;
    db.query("SELECT password FROM user WHERE email = ?", [email]).then(function (result) {
        if(result[0].password == req.body.password) {
            console.log(result[0].password);
            res.redirect("/users");
        }else{
            console.log(result[0].password);
            return false;
        }
    });
    // Example from documenation also send undefined value
    db.execute("SELECT * FROM user WHERE email = 'aaa@wp.pl;", function (err, result, fields) {
        console.log(result);
        console.log(fields);
    })
});

这是数据库连接类

const mysql = require('mysql2');

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'admin',
    database: 'weekop',
    multipleStatements: true,
    charset: 'utf8'
});

module.exports = pool.promise();

1 个答案:

答案 0 :(得分:2)

您正在使用对mysql2的promise()调用,而不是回调版本。

正确的示例应该是(来自https://www.npmjs.com/package/mysql2):

con.promise().query("SELECT * FROM user WHERE email = 'aaa@wp.pl;")
  .then(([rows, fields]) => {
      console.log(rows);
      console.log(fields);
  })
  .catch(console.log)
  .then( () => con.end());