简体   繁体   中英

Array returning undefined when it should return something else?

I am struggling with query.. I've been searching a lot, the only relevant posts I found had no answers.

row[0] returns undefined, I can't seem to find out why..

info:

As mentioned, logger.warn(rows[0]) returns undefined

rows.length returns 0

logger.warn(pool.escape(hash)) returns the correct hash(same as in DB)

logger.warn(rows[0].hash) returns undefined

This is the error in console/log file: TypeError: Cannot read property 'hash' of undefined

socket.on('hash', function(hash) {
        query('SELECT * FROM `members` WHERE `hash` = '+pool.escape(hash),
    function(err, rows) { 
            logger.warn(rows[0]) // returns "undefined"
            if((err) || (!rows.length)) return socket.disconnect();
    }

EDIT: QUERY FUNCITON

function query(sql, callback) {
if (typeof callback === 'undefined') {
    callback = function() {};
}
pool.getConnection(function(err, connection) {
    if(err) return callback(err);
    logger.info('DB Connection ID: '+connection.threadId);
    connection.query(sql, function(err, rows) {
        if(err) return callback(err);
        connection.release();
        return callback(null, rows);
    });
});

}

EDIT: Debug log

https://gyazo.com/858796b81c674ba816f974039eea1c09

EDIT: On disconnect

socket.on('disconnect', function() {
        logger.warn('Socket disconnect');
        io.sockets.emit('message', {
            type: 'logins',
            count: Object.size(io.sockets.connected)
        });
        delete users[user.email];
    })

Looking at the log, it seems that the client is sending the hash event value like this: test%40mail.com .

However, as you state in your comment, in the database the value is stored as this: test@mail.com .

Which means that before running the query, you need to URI-unescape the hash value, and then SQL-escape it, before passing it to the database:

socket.on("hash", function(hash) {
  hash = pool.escape(decodeURIComponent(hash));
  query("SELECT * FROM `members` WHERE `hash` = " + hash, function(err, rows) {
    ...
  });
});

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