Passport.js-在数据库中插入“ null”而不是用户名

时间:2018-11-24 20:26:55

标签: mysql node.js database express passport.js

使用ID,用户名和密码字段创建用户时遇到麻烦。它说未定义insertId,但是,当我在下面的代码中取消引用的代码时,它可以工作,除了在数据库中将“ null”作为用户名并将我正确地重定向到配置文件页面。有什么想法吗?

var LocalStrategy = require("passport-local").Strategy;

var mysql = require('mysql');
var bcrypt = require('bcrypt-nodejs');
var dbconfig = require('./database');
var connection = mysql.createConnection(dbconfig.connection);

connection.query('USE ' + dbconfig.database);

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

 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({
   usernameField : 'username',
   passwordField: 'password',
   passReqToCallback: true
  },
  function(req, username, password, done){
   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 is already taken'));
    }else{
     var newUserMysql = {
      username: username,
      password: bcrypt.hashSync(password, null, null),
     };

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

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

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

 passport.use(
  'local-login',
  new LocalStrategy({
   usernameField : 'username',
   passwordField: 'password',
   passReqToCallback: true
  },
  function(req, username, password, done){
   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('loginMessage', 'No User Found'));
    }
    if(!bcrypt.compareSync(password, rows[0].password))
     return done(null, false, req.flash('loginMessage', 'Wrong Password'));

    return done(null, rows[0]);
   });
  })
 );
};

任何建议/评论将不胜感激。我尝试将Id字段添加到newUserMySql变量中,但这只会使它更加烦人。

编辑:突然,即使我取消注释代码,错误也会显示未定义insertid,并关闭服务器。每次运行时似乎编译方式都不同。

0 个答案:

没有答案