简体   繁体   中英

MySQL TypeError: Cannot read property 'query' of undefined

Trying to connect to MySQL database using node but I keep getting this error below.

TypeError: Cannot read property 'query' of undefined

I believe I already all the modules and dependencies required.

MySQL connection:

var pool = mysql.createConnection;
var pool = mysql.createConnection({
    connectionLimit : 10,
    host     : 'host',
    user     : 'username',
    password : 'password',
    database : 'dbname'
});

The error stems from the line starting

app.post('/', function(request, response, mysql) {
    var username = request.body.username;
    var password = request.body.password;
    if (username && password) {
        mysql.pool.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
            if (results.length > 0) {
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('/Login_Page_V2');
            } else {
                response.send('Incorrect Username and/or Password!');
            }           
        });

I've already tried a different code but this one results in error "length" undefined.

pool.query('SELECT * FROM accounts WHERE username = ? ...

I've spent hours trying to get it to work but I am really stuck and I could use some help.

You need to create connection pool with createPool method:

    var pool  = mysql.createPool({
      connectionLimit : 10,
      host     : 'host',
      user     : 'username',
      password : 'password',
      database : 'dbname'
    });

    pool.query('.....

pool.query('SELECT * FROM accounts... is effectively the proper way.

The error: "length undefined" comes from this condition results.length > 0 .

Your IF statement should look like this:

results && results.length >= 0

That way you'll be sure that there is a results (and so an element as well) and that it's length is greater than 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM