如何使用 bcrypt 和 nodeJS 将哈希生成为全局变量

How to generate hash as a global variable using bcrypt and nodeJS

我有一个用于登录单个密码网络应用程序的反应组件。我在输入中有一个 onChange={this.setState({password: event.target.value}} 道具来更新密码。然后,当用户单击提交按钮时,它会调用此函数:

 onSubmitSignIn = () => {
  fetch('http://localhost:3000/signin', {
    method: 'post',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      password: this.state.password
    })
  })
    .then(response => response.json())
    .then(response => {
      if (response === 'true') {
        this.props.onRouteChange('home');
      }
    })
}

这是我的服务器的样子:

const express = require('express')
const app = express()
const bcrypt = require('bcrypt-nodejs')
var bodyParser = require('body-parser')
var cors = require('cors')

app.use(cors());
app.use(bodyParser.json());
app.get('/', (req, res) => res.send('Hello World!'))


bcrypt.hash("password", null, null, function(err, hash) {
console.log(hash)
});

app.post('/signin', (req, res) => {
var a = JSON.parse(req.body);
  bcrypt.compare(a.password, hashNew, function(err, res) {
if (hash === hashNew) {
    res.send(true);
} else {
    res.send(false);
}
});
})



app.listen(3000, () => console.log('App listening on port 3000!'))

我正在尝试使用 bcrypt 作为全局变量来生成哈希,以与为用户在提交时键入的密码创建的哈希进行比较。感谢您提供的所有帮助。如果有什么需要澄清的,请告诉我。

您不能在 bcrypt.hash 方法中将哈希生成为全局变量,因为这是一个异步方法。但是 bcrypt-nodejs 有一个 hashSync 方法,可用于将散列生成为全局变量。

所以你的代码变成这样:

var hash = bcrypt.hashSync("password", null);

app.post('/signin', (req, res) => {
var a = JSON.parse(req.body);
  bcrypt.compare(a.password, hashNew, function(err, res) {
if (hash === hashNew) {
    res.send(true);
} else {
    res.send(false);
}
});
})

请注意,使用同步函数进行散列会影响性能,因此不推荐使用。