问题描述
所以我目前正在学习 mosh Hamdani 的 Mastering React 课程,后端开发给我带来了许多问题。最近一个是错误:“未定义没有给出回调函数”。我正在尝试使用 bcrypt 注册一个新用户。
要解决我尝试使用的问题:
const salt = bcrypt.genSalt(10,function(_err,salt) {
bcrypt.hash(user.name,salt,hash) {
// Store hash in your password DB.
});
});
来自 https://www.npmjs.com/package/bcrypt 甚至那也没有用。
如果有人可以帮助我,将不胜感激。
这是我的 user.js 文件:
const auth = require("../middleware/auth");
const bcrypt = require("bcrypt-nodejs");
const _ = require("lodash");
const { User,validate } = require("../models/user");
const express = require("express");
const router = express.Router();
router.get("/me",auth,async (req,res) => {
const user = await User.findById(req.user._id).select("-password");
res.send(user);
});
router.post("/",res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({ email: req.body.email });
if (user) return res.status(400).send("User already registered.");
user = new User(_.pick(req.body,["name","email","password"]));
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password,salt);
await user.save();
const token = user.generateAuthToken();
res
.header("x-auth-token",token)
.send(_.pick(user,["_id","name","email"]));
});
module.exports = router;
这是我在终端中收到的警告:
(node:7776) DeprecationWarning:当前 URL 字符串解析器已被弃用,并将在未来版本中删除。要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。 (node:7776) 弃用警告:当前的服务器发现和监控引擎已被弃用,并将在未来版本中删除。要使用 新的服务器发现和监控引擎,将选项 { useUnifiedTopology: true } 传递给 MongoClient 构造函数。 信息:侦听端口 3900... (节点:7776)弃用警告:不推荐使用 collection.ensureIndex。改用 createIndexes。
解决方法
好吧,我之前没有意识到 bcrypt-nodejs 不再处于活动状态 https://www.npmjs.com/package/bcrypt-nodejs。而是使用 bcryptjs https://www.npmjs.com/package/bcrypt。
我还将代码升级为:
bcrypt.genSalt(10,function (_err,salt) {
bcrypt.hash(user.name,salt,hash) {
// Store hash in your password DB.
user.password = hash;
});
});