我是node的新手,我下载了一个注册示例,显示错误:
“无法读取未定义的属性'insertId'”
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
connection.query("SELECT * FROM singup WHERE id = ? ",[id], function(err, rows){
done(err, rows[0]);
});
});
passport.use(
'local-signup',
new LocalStrategy({
fullnameField : 'fullname',
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true
},
function(req,fullname, username, password, done) {
connection.query("SELECT * FROM singup 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 {
var newUserMysql = {
id:"2",
fullname: fullname,
username: username,
password: bcrypt.hashSync(password, null, null)
};
var insertQuery = "INSERT INTO singup (fullname, username, password ) values (?,?,?)";
connection.query(insertQuery,[newUserMysql.fullname, newUserMysql.username, newUserMysql.password],function(err, rows) {
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
}
});
})
);
//TypeError: Cannot read property 'insertId' of undefined
at Query.<anonymous> (E:\testing\nodejs\config\passport.js:71:48)
at Query.<anonymous> (E:\testing\nodejs\node_modules\mysql\lib\Connection.js:502:10)
at Query._callback (E:\testing\nodejs\node_modules\mysql\lib\Connection.js:468:16)
at Query.Sequence.end (E:\testing\nodejs\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query.ErrorPacket (E:\testing\nodejs\node_modules\mysql\lib\protocol\sequences\Query.js:90:8)
at Protocol._parsePacket (E:\testing\nodejs\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (E:\testing\nodejs\node_modules\mysql\lib\protocol\Parser.js:76:12)
at Protocol.write (E:\testing\nodejs\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (E:\testing\nodejs\node_modules\mysql\lib\Connection.js:91:28)
at Socket.<anonymous> (E:\testing\nodejs\node_modules\mysql\lib\Connection.js:502:10)
答案 0 :(得分:1)
首先,请务必检查错误! 如果有错误,则行字段将是未定义的。 (似乎是这种情况)
如果没有错误,则记录行字段以查看其结构。
rows字段可能是一个数组,因此为了访问insertId,您可以尝试更改
来自
newUserMysql.id = rows.insertId
收件人
newUserMysql.id = rows[0].insertId