无法使用ReactJS和bcryptjs

时间:2017-12-07 16:42:02

标签: reactjs hash bcrypt

我正在尝试使用bcryptjs库在我的项目中散列密码,但是当我添加散列过程所需的函数时,我遇到了一些错误。我按照此链接中的说明操作:bcryptjs instructions

我的想法是,当我调用SubmitClick函数时,我必须对提供的密码进行散列,然后使用fetch将其添加到我的数据库中。这是我的CreateUser.js页面的代码:

import React, { Component } from 'react';
import bcrypt from 'bcryptjs';

class CreateUser extends Component {

  constructor(props){
    super(props);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
              console.log(hash); 
          });
      });

      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => this.setState({id : parsedJSON._id}, function(){
        this.props.history.push({
          pathname : '/get',
          state : { id : this.state.id }
        });
      }))
      .catch(error => alert('Check your data! Some of the values passed aren`t valid'))
    }
  }

  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }

  changeEmail(event){
    this.setState({email : event.target.value})
  }

  changeFname(event){
    this.setState({first_name : event.target.value})
  }

  changeLname(event){
    this.setState({last_name : event.target.value})
  }

  changePhone(event){
    this.setState({personal_phone : event.target.value})
  }

  changePassword(event){
    this.setState({password : event.target.value})
  }

  changeReTPassword(event){
    this.setState({reTypepassword : event.target.value})
  }

  render() {
    return (
      <div id="layout">
        <div id="main">
          <div className="App-header">
              <label htmlFor="title">Create User</label> 
          </div>
          <div className="content" id="content">
            <div className="infos">
              <input id="email" type="text" name="email" placeholder="Email" 
              onChange = {(event)=> this.changeEmail(event)}/>
            </div>
            <div className="infos">
              <input id="f_name" type="text" name="F_name" placeholder="First Name" 
              onChange = {(event)=> this.changeFname(event)}/>
            </div>
            <div className="infos">
              <input id="l_name" type="text" name="L_name" placeholder="Last Name" 
              onChange = {(event)=> this.changeLname(event)}/>
            </div>
            <div className="infos">
              <input id="phone" type="text" name="L_name" placeholder="Personal Phone" 
              onChange = {(event)=> this.changePhone(event)}/>
            </div>
            <div className="infos">
              <input id="senha" type="password" name="senha" placeholder="Password" 
              onChange = {(event)=> this.changePassword(event)}/>
            </div>
            <div className="infos">
              <input id="senha" type="password" name="senha" placeholder="Re-type password" 
              onChange = {(event)=> this.changeReTPassword(event)}/>
            </div>
            <div className="buttons">                                  
              <button type="submit" onClick={(event) => this.SubmitClick()} className="buttonsUser">Submit</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default CreateUser;

如果删除代码的以下部分,代码将完美运行,无需散列:

  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.props.password, salt, function(err, hash) {
          console.log(hash); 
      });
  });

但是在那部分,我正面临着这个错误:

> CreateUser.js:26 Uncaught TypeError: Cannot read property 'state' of undefined
    at CreateUser.js:26
    at bcrypt.js:155
    at run (setImmediate.js:40)
    at runIfPresent (setImmediate.js:69)
    at onGlobalMessage (setImmediate.js:109)

我在StackOverflow问题中搜索并发现了一些类似于我的问题,我尝试使用每个问题中提出的解决方案,但没有任何改变。以下是问题链接供参考:Question1 Question2 Question3 Question4

我试图在类构造函数中绑定我的函数,如下所示,但是得到了同样的错误。

  constructor(props){
    super(props);
    this.SubmitClick = this.SubmitClick.bind(this);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

我尝试将内联函数绑定,在这种情况下,当我点击按钮时没有发生任何事情,这很奇怪。

    <div className="buttons">                                  
      <button type="submit" onClick={(event) => this.SubmitClick.bind(this)} className="buttonsUser">Submit</button>
    </div>

我不知道我的代码有什么问题,有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您正在丢失传递给genSalt的回调方法中的上下文:

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash); 
    });
});

<强>解决方案:

一种方法是在这里使用arrow function

bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(this.state.password, salt, (err, hash) => {
          console.log(hash); 
    });
});

或使用.bind(this)

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash); 
    });
}.bind(this));

或使用额外变量,并使用该变量代替this

SubmitClick(){
    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    }else {

        let that = this;    //here

        bcrypt.genSalt(10, function(err, salt) {
            bcrypt.hash(that.state.password, salt, function(err, hash) {
                console.log(hash); 
            });
        });
    }
    .....
}

答案 1 :(得分:1)

您需要bind回调或this不会设置:

  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash); 
      });
  }.bind(this));

或使用箭头功能:

  bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash); 
      });
  });