猿问

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

这是我的代码


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

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


HUWWW
浏览 168回答 1
1回答

蓝山帝景

在对象字面量中,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 => {&nbsp; &nbsp; // You have it now, you can build and use the object&nbsp; &nbsp; const user = {&nbsp; &nbsp; &nbsp; &nbsp; first: "Donald",&nbsp; &nbsp; &nbsp; &nbsp; last: "Trump",&nbsp; &nbsp; &nbsp; &nbsp; password : hashedPassword,&nbsp; &nbsp; &nbsp; &nbsp; greetUser() { // Note I removed the parameter you weren't using here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Hi, ${this.first} ${this.last} ${this.password}`);&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; };&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; user.greetUser(); // Note I removed the unused argument here}).catch(error => {&nbsp; &nbsp; // Handle/report the error...});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答