简体   繁体   English

“错误:非法 arguments:字符串,未定义”并在节点 JS 中停止服务器

[英]"Error: Illegal arguments: string, undefined" and stop server in node JS

I'm trying to build logging application in node JS.我正在尝试在节点 JS 中构建日志记录应用程序。 in here password authentication app do not work properly.在这里密码验证应用程序不能正常工作。 when i enter username and password it occur following error and stop server.当我输入用户名和密码时,出现以下错误并停止服务器。

this is the error.

在此处输入图像描述

Here is the code for authentication part这是身份验证部分的代码

passport.use(new LocalStrategy(
function(username, password, done) {
    User.getUserByUsername(username, function(err, user){
       if(err) throw err;
       if (!user) {
           return done(null, false, {message: 'Unknown user'});
       } 

       User.comparePassword(password, user.password, function(err, isMatch){
           if(err) throw err;
           if (isMatch) {
               return done(null, user);
           } else {
               return done(null, false, {message: 'Invalid password'});
           }
       });
    });
}));

This code work for Unknown user.此代码适用于未知用户。 but it is not working for comparing username and password.但它不适用于比较用户名和密码。 i cannot see any bug in here.我在这里看不到任何错误。 i want a help for solve this.我需要帮助解决这个问题。

I found the problem in here.我在这里发现了问题。 it is not things regarding the code.这不是关于代码的事情。

The thing is i had registered two users with same user name and different password.问题是我用相同的用户名和不同的密码注册了两个用户。 then when i tried to login with the user name and one password it occurred this error and stop the server.然后当我尝试使用用户名和一个密码登录时,它发生了这个错误并停止了服务器。

Because there is embarrassing situation with find password to username that user entered.因为在用户输入的用户名中查找密码存在尴尬的情况。 because there are two password with same username.因为有两个密码相同的用户名。

In the name of the universe programmer以宇宙程序员的名义

in my case i forgot to select the password because in database the password was ((select: false))就我而言,我忘记选择密码,因为在数据库中密码是 ((select: false))

this code for app此应用程序代码

const user = await User.findOne({email}).select("+password")

i forgot to append the ((.select("+password")))to the findOne我忘了将 ((.select("+password"))) 附加到 findOne

and I received this error ;我收到了这个错误; Error: Illegal arguments: string, undefined错误:非法参数:字符串,未定义

and this code for database和这个数据库代码

const User = new mongoose.Schema({
    username:{
        type:String,
        required: [true,"نام کاربری ضروری است"]
    },
    email:{
        type:String,
        required: [true,"رایانامه ضروری است"],
        unique: true,
        match:[
            /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,3})$/,
            "لطفا یک رایانامه صحیح وارد کنید"
        ]
    },
    password:{
        type:String,
        required:[true,"رمز ضروری است"],
        minlegth: 5,
        select: false
    }
})

In my case, I was using arrow function就我而言,我使用的是箭头函数

userSchema.methods.comparePassword = async (enterdPassword) => {
  return await bcrypt.compare(enterdPassword, this.password);
};

which I converted to normal function我转换为正常功能

userSchema.methods.comparePassword = async function (enterdPassword) {
  return await bcrypt.compare(enterdPassword, this.password);
};

that solved the problem解决了这个问题

In my case, I'm using social signin/signup.就我而言,我正在使用社交登录/注册。 When the user is signing up using a social login option, the value of the password stored is "NULL".当用户使用社交登录选项进行注册时,存储的密码值为“NULL”。

So I just added this little check :所以我只是添加了这个小检查:

  comparePassword: function(password, user){
    if (!user.password)
      return false;
    return bcrypt.compareSync(password, user.password);
  }

At

"models/user.js" “模型/user.js”

Inside comparePassword里面比较密码

module.exports.comparePassword = (candidatePassword, hash, callback) => {...) 

Add this code:添加此代码:

bcrypt.hash(candidatePassword, 10, (err, hash) => {
    if(err) {
        throw err;
    }
    bcrypt.compare(candidatePassword, hash, (err, isMatch) => {
        if(err) {
            throw err;
        }
        callback(null, isMatch);
    });
});

Here We are grabbing username and password from the sign in page AND finding our user by the username from the database and then Matching its encrypted password with an entered password by the user在这里,我们从登录页面获取用户名和密码,并通过数据库中的用户名找到我们的用户,然后将其加密密码与用户输入的密码进行匹配

passport.use(new LocalStrategy(
    (username,password,done)=> {
        db.users.findOne({username: username},(err, user)=> {
            if(err) return done(err);

            if(!user) {
                return done(null,false,{message: 'Incorrect Username'});
            }
            bcrypt.compare(password, user.password,(err,isMatch)=> {
                if(err) return done(err);
                if(isMatch) {
                    return done(null, user);
                } else {
                    return done(null, false,{message: 'Incorrect Password'});
                }
            });
         });
      }
   ));

You need to apply await to your salt and password assignments too.您也需要将 await 应用于盐和密码分配。

Like this,像这样,

const salt = await bcrypt.genSaltSync(10);
const password = await req.body.password;

You can write a code like this: After this.findOne({ select: []........})... I hope this is helpful您可以编写这样的代码:After this.findOne({ select: [].......})... 希望对您有所帮助

 async validateUserPassword(loginDto: AuthLoginDto): Promise<User> { const { mobile, email, password } = loginDto; const user = await this.findOne({ select: ['id', 'email', 'mobile', 'password', 'salt', 'status', 'logged_at'], where: [ { mobile: mobile }, { email: email } ] }); if (user && await user.validatePassword(password)) { const logged_at = { logged_at: new Date() } await this.update({ id: user.id }, logged_at) return user; } else { return null; } } async validatePassword(password: string): Promise<boolean> { const hash = await bcrypt.hash(password, this.salt); return hash === this.password; }

In my own case, I just want to check if the old password matches the password in Db but got the error, here is my code below:在我自己的情况下,我只想检查旧密码是否与 Db 中的密码匹配但出现错误,这是我的代码如下:

changePassword = asyncHandler (async (req: IGetUserAuthInfoRequest, res: Response) => {
  const user = await User.findById(req.user._id)
  const {oldPassword, password} = req.body

  if(!user) {
    res.status(400)
    throw new Error("User not found, please signup")
  }

  // Validate
  if(!oldPassword || !password) {
    res.status(400)
    throw new Error("Please add old and new password")
  }

  // Check if old password matches password in DB
  const passwordIsCorrect = await bcrypt.compare(oldPassword, user.password)

  // Save new password
  if(user && passwordIsCorrect) {
    user.password = password
    await user.save()
    res.status(200).send("Password change successful")
  } else {
    res.status(400)
    throw new Error("Old password is incorrect")
  }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM