简体   繁体   English

在javaScript中如何导出工作。 哈希未定义的bcryptjs

[英]how doe export work in javaScript wold. hash undefined bcryptjs

Let's say we have two file, user.js users.js in user.js we have. 假设我们有两个文件,即user.js中的user.js users.js。 Why can we do module.exports.. we can use in it diff .js file? 为什么我们可以做module.exports ..我们可以在其中使用diff .js文件? what does "@returns Promise If callback has been omitted" means it is from the bcrypt.genSalt function? "@returns Promise If callback has been omitted"是什么意思意味着它来自bcrypt.genSalt函数? I also have a github repo, so please take a look if you have a bit of time. 我也有一个github仓库,所以如果有时间请看一下。 after cloning it 克隆后

stuck in terminal 卡在终端

    result { error: null,
  value:
   { email: 'max@mail.com',
     username: 'max',
     password: '1234',
     confirmationPassword: '1234' },
  then: [Function: then],
  catch: [Function: catch] }
hash undefined


const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');


const userSchema = new Schema({
  email: String,
  username: String,
  password: String
});


const User = mongoose.model('user', userSchema);
module.exports = User;
module.exports.hashPassword = (password) => {
 return hash = bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(password, salt, function(err, hash) {
    });
});
}; 

in users.js we have have 在users.js中,我们有

const express = require('express');
const router = express.Router();
const Joi = require('joi');
const User = require('../models/user');   



const userSchema = Joi.object().keys({
  email:Joi.string().email().required(),
  username:Joi.string().required(),
  password:Joi.string().regex(/^[a-zA-Z0-9]{3,15}$/).required(),
  confirmationPassword:Joi.any().valid(Joi.ref('password')).required()
});



router.route('/register')
  .get((req, res) => {
    res.render('register');
  })
  .post(async (req, res, next) => {
    try{
        const result =  Joi.validate(req.body,userSchema);
        console.log('result',result);

        if(result.error) {
          req.flash('error', 'Data is not valid, please try again');
          res.redirect('/users/register');
          return;
        //console.log('result',result);
      }
      //  checking if email is already taken
      const user =  await User.findOne({'email':result.value.email });
        if (user){
          req.flash('error','Email is already in use');
          res.redirect('/users/register');
          return;
        }


     // console.log('hash',hash);

      // Hash the password
      const hash = await User.hashPassword(result.value.password); 
      console.log('hash',hash);

  } catch(error) {
    next(error);
    }
  });
module.exports = router;

based the example given by bcrypt 基于bcrypt给出的示例

var bcrypt = require('bcryptjs');
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("B4c0/\/", salt, function(err, hash) {
        // Store hash in your password DB.
    });
});

adding pic for mongo db 为mongo db添加图片 在此处输入图片说明

I think the problem lies in this line: 我认为问题出在这一行:

const hash = await User.hashPassword(result.value.password);

This implies that User.hashPassword(result.value.password) should be returning a promise (but it returns a reference to the wrong promise). 这意味着User.hashPassword(result.value.password)应该返回一个诺言(但它返回对错误诺言的引用)。

module.exports.hashPassword = (password) => {
    return hash = bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(password, salt, function (err, hash) {});
    });
};

Perhaps modifying the above to return a promise may help.. Like so: 也许修改以上内容以返回承诺可能会有所帮助。

module.exports.hashPassword = (password) => {
    var salt = await bcrypt.genSalt(10);
    return bcrypt.hash(password, salt);
};

To answer your question about @returns Promise If callback has been omitted : 回答有关@returns Promise If callback has been omitted的问题@returns Promise If callback has been omitted

Bcrypt methods are asynchronous. Bcrypt方法是异步的。 Which means they return immediately and process in the background. 这意味着它们会立即返回并在后台处理。 When the result is available, the function makes this available to the calling code either via a callback function or a promise. 当结果可用时,该函数可以通过回调函数或promise将其提供给调用代码。

Consider the following API for genSalt from the docs: 考虑以下来自genSalt API:

genSalt(rounds, minor, cb) genSalt(回合,次要,cb)

rounds - [OPTIONAL] - the cost of processing the data. 四舍五入-[可选]-处理数据的成本。 (default - 10) (默认-10)

minor - [OPTIONAL] - minor version of bcrypt to use. minor-[可选]-要使用的bcrypt的次要版本。 (default - b) (默认-b)

cb - [OPTIONAL] - a callback to be fired once the salt has been generated. cb-[可选]-生成盐后将触发的回调。 uses eio making it asynchronous. 使用eio使其异步。 If cb is not specified, a Promise is returned if Promise support is available. 如果未指定cb,则在有Promise支持的情况下返回Promise。

  err - First parameter to the callback detailing any errors. salt - Second parameter to the callback providing the generated salt. 

What that says is genSalt can take three arguments: genSalt(rounds, minor, cb) genSalt可以采用三个参数: genSalt(rounds, minor, cb)

Sample using callbacks 使用回调的样本

If the calling code wants the result via a callback, it can pass a function which looks like function(err, salt){} as the cb parameter. 如果调用代码希望通过回调获得结果,则可以传递一个类似于function(err, salt){}作为cb参数。

 bcrypt.genSalt(rounds, minor, function(err, salt){
     if(err){
         //Handle error
         return;
     }
     // Salt is available here
     console.log(salt);
 });

Sample using promises 样品使用诺言

If the cb parameter is not passed (null or undefined) the function returns a Promise instead. 如果未传递cb参数(空或未定义),该函数将返回Promise。

 var promise = bcrypt.genSalt(rounds, minor);
 promise
     .then(function(salt){
         // Salt is available here
         console.log(salt);
     })
     .catch(function(err){
         // Handle error
     });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM