Javascript 使用bcrypt和对象分配的密码哈希

Javascript 使用bcrypt和对象分配的密码哈希,javascript,hash,bcrypt,assign,salt,Javascript,Hash,Bcrypt,Assign,Salt,我需要将清除的密码替换为散列的密码。我正在使用bcryptjs来帮助我解决这个问题 我已经尝试分配了清除散列密码中的密码,但是我的bash出现了一个错误 我试图使其工作的代码: const bcrypt = require('bcryptjs'); const students = require('./students1.json'); const fs = require('fs'); let secureUsers = []; for (let student of students)

我需要将清除的密码替换为散列的密码。我正在使用bcryptjs来帮助我解决这个问题

我已经尝试分配了清除散列密码中的密码,但是我的bash出现了一个错误

我试图使其工作的代码:

const bcrypt = require('bcryptjs');
const students = require('./students1.json');
const fs = require('fs');

let secureUsers = [];
for (let student of students) {
    let salt = bcrypt.genSaltSync(10);
    let passHash = bcrypt.hashSync(student.password, salt);
    Object.assign(student.password, passHash);
    secureUsers.push(secStudent);
}
fs.writeFileSync('secStudents.json', JSON.stringify(secureUsers, null, 2));
console.log('wrote file!');
我得到的错误是:

$ node bcryptExample.js
C:\Users\mziad\assignment-mziadeh1\servers\bcryptExample.js:13
    Object.assign(student.password, passHash);
           ^

TypeError: Cannot assign to read only property '0' of object '[object String]'
    at Function.assign (<anonymous>)
    at Object.<anonymous> (C:\Users\mziad\assignment-mziadeh1\servers\bcryptExample.js:13:12)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)


我需要密码与哈希代码交换,因此我尝试分配它。但是我遇到了一个我不理解的错误,我现在无法发现代码中的任何问题。

您似乎误解了Object.assign函数的工作原理。 Object.assign函数的作用是,它遍历源参数(第一个参数后面的参数)的每个属性,并在第一个参数中覆盖它

示例中的问题是,您试图调用Object.assign,其参数为字符串
Object.assign('abc','def')
。JavaScript中的字符串文字实际上是一个字符数组,并且是一个以索引作为属性的对象中的数组。默认情况下,无法重新分配字符串属性(索引)(可写:false)

下面是一个演示:

var a = 'abc';
console.log(a[0]) // outputs 'a'

var descriptor = Object.getOwnPropertyDescriptor(a, 0)
console.log(descriptor)
//outputs
/*
{ value: 'a',
  writable: false,
  enumerable: true,
  configurable: false }
*/

Object.assign('abc', 'def');// throws Cannot assign to read only property '0' of object '[object String]'
如您所见,writable设置为false,这意味着您无法重新分配字符串中的每个字符。这解释了为什么错误消息说字符串“abc”的属性“0”不能分配新值

因此,解决方案是执行
student.password=passHash
而不是
Object.assign(student.password,passHash)

var a = 'abc';
console.log(a[0]) // outputs 'a'

var descriptor = Object.getOwnPropertyDescriptor(a, 0)
console.log(descriptor)
//outputs
/*
{ value: 'a',
  writable: false,
  enumerable: true,
  configurable: false }
*/

Object.assign('abc', 'def');// throws Cannot assign to read only property '0' of object '[object String]'