【问题标题】:Why is rows undefined?为什么行未定义?
【发布时间】:2018-07-03 16:02:29
【问题描述】:

使用 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:无法读取未定义的属性“id” 在 Query._callback (M:\server\config\passport.js:70:55) 在 Query.Sequence.end (M:\server\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24) 在 Query.ErrorPacket (M:\server\node_modules\mysql\lib\protocol\sequences\Query.js:90:8) 在 Protocol._parsePacket (M:\server\node_modules\mysql\lib\protocol\Protocol.js:279:23) 在 Parser.write (M:\server\node_modules\mysql\lib\protocol\Parser.js:76:12) 在 Protocol.write (M:\server\node_modules\mysql\lib\protocol\Protocol.js:39:16) 在套接字。 (M:\server\node_modules\mysql\lib\Connection.js:103:28) 在 emitOne (events.js:116:13) 在 Socket.emit (events.js:211:7) 在 addChunk (_stream_readable.js:263:12) 在 readableAddChunk (_stream_readable.js:250:11) 在 Socket.Readable.push (_stream_readable.js:208:10) 在 TCP.onread (net.js:594:20)

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

[编辑] 考虑到答案后,产生了以下错误(因为rows.insertId 仍然未定义):

错误:无法将用户序列化到会话中 通过 (M:\server\node_modules\passport\lib\authenticator.js:281:19) 在序列化 (M:\server\node_modules\passport\lib\authenticator.js:286:7) 在 M:\server\config\passport.js:24:9 通过 (M:\server\node_modules\passport\lib\authenticator.js:294:9) 在 Authenticator.serializeUser (M:\server\node_modules\passport\lib\authenticator.js:299:5) 在 SessionManager.logIn (M:\server\node_modules\passport\lib\sessionmanager.js:14:8) 在 IncomingMessage.req.login.req.logIn (M:\server\node_modules\passport\lib\http\request.js:50:33) 在 Strategy.strategy.success (M:\server\node_modules\passport\lib\middleware\authenticate.js:248:13) 在已验证 (M:\server\node_modules\passport-local\lib\strategy.js:83:10)

【问题讨论】:

  • err 是否包含某些内容?
  • @El_Matella nope 错误为空。现在重新运行代码产生了另一个错误:Error: Failed to serialize user into session
  • newUserMysql 来自哪里?
  • @Ravi 它只是 JSON 格式的本地变量。 var newUserMysql = {username: username, password : password};
  • @Valamorde 你能分享一下json吗?

标签: javascript node.js express passport-local


【解决方案1】:

据我了解,与MySQL无关

您共享的 JSON 没有 id

var newUserMysql = {用户名:用户名,密码:密码};

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

newUserMysql.id = rows.insertId;

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

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

【讨论】:

  • 不,不是这样!我试过了,错误仍然是Failed to serialize user into session。会不会是`id`字段被填零了?
  • @Valamorde 因为您的序列化不期望id。您不再被提及例外。现在,我们没有您的应用程序的完整图片。无论您要分享什么,我们都会相应地回答。
  • @Valamorde 这不是你应该完全改变你的问题的方式。如果您的问题得到解决,则会遇到其他问题。然后,您应该接受答案并使用其他详细信息创建新帖子。现在,我的回答内容将完全改变
  • @Valamorde 另外,不要忘记回复您的问题。否则,人们会感到困惑。
  • @Valamorde 我已经回滚到最初的问题。
【解决方案2】:

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

newUserMysql = rows.insertId;

进入这个:

newUserMysql = rows[0].insertId;

问题已成功解决。

【讨论】:

  • 请注意,如果 rows 未定义或为空数组,这将失败。所以你可能想以某种方式处理它。
  • @Bergur 通常是的,在我的情况下会引发错误,因为我在没有指定元素索引的情况下访问元素属性。一旦这个问题得到修复,它现在已经有近 8 个月没有被定义或为空了:p
猜你喜欢
  • 1970-01-01
  • 2011-05-05
  • 2020-05-12
  • 2021-07-22
  • 2021-07-18
  • 2012-06-21
  • 2022-01-05
  • 2017-10-10
相关资源
最近更新 更多