[英]Why I got Illegal arguments error with simple hash function?
This is my code这是我的代码
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);
I run我跑
node --trace-warnings index.js
Hi, Donald Trump [object Promise]
(node:15222) UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, object
I expected hashed password.我期望散列密码。 Why does terminal point to illegal arguments?
为什么终端指向非法参数?
In an object literal, password : bcrypt.hash(this.password, salt)
calls bcrypt.hash
and assigns its return value to the password
property.在对象字面量中,
password : bcrypt.hash(this.password, salt)
调用bcrypt.hash
并将其返回值分配给password
属性。 In the code you've shown, this
doesn't refer to the object being created, it refers to the same thing this
refers to where the object literal is being created (the top level of the module).在您显示的代码中,
this
不是指正在创建的对象,它指的是与this
指的是创建对象文字的位置(模块的顶层)相同的东西。 Since that doesn't have a password
property, you're passing undefined
to the function.由于它没有
password
属性,因此您将undefined
传递给函数。
bcrypt.hash
also returns a promise, as you can see from the output you get before the unhandled promise rejection. bcrypt.hash
还返回一个承诺,正如您从未处理的承诺拒绝之前获得的输出中看到的那样。
Your user
object is being populated with hardcoded values, so you may have meant to do something like this:您的
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.