繁体   English   中英

为什么我使用简单的哈希函数出现非法参数错误?

[英]Why I got Illegal arguments error with simple hash function?

这是我的代码

const bcrypt = require('bcryptjs');
const salt = bcrypt.genSalt(11);

const user = {
    first: "Donald",
    last: "Trump",
    password : bcrypt.hash(this.password, salt),
    greetUser(password) {
      console.log(`Hi, ${this.first} ${this.last} ${this.password}`);
    },
  };
  
  let password = 'secondhand01';
  user.greetUser(password);

我跑

node --trace-warnings index.js

Hi, Donald Trump [object Promise]
(node:15222) UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, object

我期望散列密码。 为什么终端指向非法参数?

在对象字面量中, password : bcrypt.hash(this.password, salt)调用bcrypt.hash并将其返回值分配给password属性。 在您显示的代码中, this不是指正在创建的对象,它指的是与this指的是创建对象文字的位置(模块的顶层)相同的东西。 由于它没有password属性,因此您将undefined传递给函数。

bcrypt.hash还返回一个承诺,正如您从未处理的承诺拒绝之前获得的输出中看到的那样。

您的user对象正在填充硬编码值,因此您可能打算执行以下操作:

const bcrypt = require('bcryptjs');
const salt = bcrypt.genSalt(11);

bcrypt.hash("secondhand01", salt) // <=== Encrypt the password
.then(hashedPassword => {
    // You have it now, you can build and use the object
    const user = {
        first: "Donald",
        last: "Trump",
        password : hashedPassword,
        greetUser() { // Note I removed the parameter you weren't using here
          console.log(`Hi, ${this.first} ${this.last} ${this.password}`);
        },
    };
      
    user.greetUser(); // Note I removed the unused argument here
})
.catch(error => {
    // Handle/report the error...
});

暂无
暂无

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

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