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

6ioyuze2  于 2021-06-17  发布在  Mysql
关注(0)|答案(0)|浏览(242)

无法创建具有id、用户名和密码字段的用户。它说insertid没有定义,但是,当我在下面的代码中取消引用引用引用的代码时,它有点工作,只是它在数据库中把“null”作为用户名,并正确地将我重定向到profile页。有什么想法吗?

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]);
   });
  })
 );
};

如有任何建议/意见,将不胜感激。我尝试过在newusermysql变量中添加一个id字段,但这会更麻烦。
edit:突然间,即使我取消了代码注解,错误也会显示insertid未定义,并关闭服务器。每次我运行它时编译的方式似乎都不一样。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题