簡體   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