为什么行未定义?

Why is rows undefined?

使用 Passport(Local-Signup) 创建用户注册功能,代码如下:

// config/passport.js

// load all the things we need
var LocalStrategy   = require('passport-local').Strategy;

// load up the user model
var mysql = require('mysql');
var bcrypt = require('bcrypt-nodejs');
var dbconfig = require('./database');
var connection = mysql.createConnection(dbconfig.connection);

connection.query('USE ' + dbconfig.database);
// expose this function to our app using module.exports
module.exports = function(passport) {


    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        connection.query("SELECT * FROM users WHERE id = ? ",[id], function(err, rows){
            done(err, rows[0]);
        });
    });


    passport.use(
        'local-signup',
        new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'username',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, username, password, done) {
            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows) {
                if (err)
                    return done(err);
                if (rows.length) {
                    return done(null, false, req.flash('signupMessage', 'That username is already taken.'));
                } else {
                    // if there is no user with that username
                    // create the user
                    var newUserMysql = {
                        username: username,
                        password: bcrypt.hashSync(password, null, null)  // use the generateHash function in our user model
                    };

                    var insertQuery = "INSERT INTO users ( username, password ) values (?,?)";

                    connection.query(insertQuery,[newUserMysql.username, newUserMysql.password],function(err, rows) {
                        newUserMysql.id = rows.insertId;

                        return done(null, newUserMysql);
                    });
                }
            });
        })
    );

抛出以下错误:

TypeError: Cannot read property 'id' of undefined at Query._callback (M:\server\config\passport.js:70:55) at Query.Sequence.end (M:\server\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24) at Query.ErrorPacket (M:\server\node_modules\mysql\lib\protocol\sequences\Query.js:90:8) at Protocol._parsePacket (M:\server\node_modules\mysql\lib\protocol\Protocol.js:279:23) at Parser.write (M:\server\node_modules\mysql\lib\protocol\Parser.js:76:12) at Protocol.write (M:\server\node_modules\mysql\lib\protocol\Protocol.js:39:16) at Socket. (M:\server\node_modules\mysql\lib\Connection.js:103:28) at emitOne (events.js:116:13) at Socket.emit (events.js:211:7) at addChunk (_stream_readable.js:263:12) at readableAddChunk (_stream_readable.js:250:11) at Socket.Readable.push (_stream_readable.js:208:10) at TCP.onread (net.js:594:20)

使用 console.log(rows); returns undefined。我该如何解决这个问题?

[编辑] 考虑到答案后,产生了以下错误(因为 rows.insertIdstill undefined):

Error: Failed to serialize user into session at pass (M:\server\node_modules\passport\lib\authenticator.js:281:19) at serialized (M:\server\node_modules\passport\lib\authenticator.js:286:7) at M:\server\config\passport.js:24:9 at pass (M:\server\node_modules\passport\lib\authenticator.js:294:9) at Authenticator.serializeUser (M:\server\node_modules\passport\lib\authenticator.js:299:5) at SessionManager.logIn (M:\server\node_modules\passport\lib\sessionmanager.js:14:8) at IncomingMessage.req.login.req.logIn (M:\server\node_modules\passport\lib\http\request.js:50:33) at Strategy.strategy.success (M:\server\node_modules\passport\lib\middleware\authenticate.js:248:13) at verified (M:\server\node_modules\passport-local\lib\strategy.js:83:10)

据我了解,与MySQL

无关

您分享的JSON没有id

var newUserMysql = {username: username, password : password};

然而,您正在尝试访问 id,这就是您得到 undefined

的原因
newUserMysql.id = rows.insertId;

要解决此问题,您需要将 id 添加到 JSON。

var newUserMysql = {username: "username", password : "password", id:""};

答案一直在我眼皮底下。我所要做的就是改变这个:

newUserMysql = rows.insertId;

进入这个:

newUserMysql = rows[0].insertId;

问题已成功解决。