问题描述
我正在使用 nodejs and mongodb
处理后端。编码 authentication
部分后,我遇到了未知问题,我认为它来自 bcrypt
:(
请看我的代码。
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const validator = require("validator");
require("dotenv").config();
const userSchema = mongoose.Schema(
{
email: {
type: String,required: true,unique: true,trim: true,lowercase: true,validate(value) {
if (!validator.isEmail) {
throw new Error("Invalid Email");
}
},},password: {
type: String,role: {
type: String,enum: ["user","admin"],default: "user",name: {
type: String,maxlength: 21,phone: {
required: true,type: Number,maxlength: 12,{
timestamps: true,);
userSchema.pre("save",async function (next) {
if (this.isModified("password")) {
// hash the password
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(this.password,salt);
this.password = hash;
}
next();
});
userSchema.methods.generatetoken = function () {
const userObj = { id: this._id.toHexString(),email: this.email };
const token = jwt.sign(userObj,process.env.DB_SECRET,{
expiresIn: "3d",});
return token;
};
userSchema.statics.emailTaken = async function (email) {
const user = await this.findOne({ email });
return !!user;
};
const User = mongoose.model("User",userSchema);
module.exports = {
User,};
用户 API 代码(请避免那些控制台日志语句,因为我添加它们是为了调试目的)-
const express = require("express");
const router = express.Router();
require("dotenv").config();
const { User } = require("../../models/usermodel");
const bcrypt = require("bcrypt");
// const comparePassword = async (userPassword) => {
// console.log("Comparing password with bcrypt");
// const match = await bcrypt.compare(userPassword,this.password);
// console.log(match);
// return match;
// };
router.route("/signup").post(async (req,res) => {
const { email,password,name,phone } = req.body;
console.log(req.body);
try {
// Check if user email exists
if (await User.emailTaken(email)) {
return res.status(400).json({ message: "Email already exists" });
}
// create user instance and hash password
const user = new User({
email: email,password: password,name: name,phone: phone,});
// generate jwt token
console.log("user is saving");
const token = user.generatetoken();
const userDoc = await user.save();
// send email
// save....send token with cookie
res.cookie("access-token",token).status(200).send(returnUserDoc(userDoc));
} catch (error) {
res
.status(400)
.json({ message: "Error while creating user",error: error });
}
});
router.route("/login").post(async (req,res) => {
try {
// Find user
console.log("Finding User........");
let user = await User.find({ email: req.body.email });
if (!user) {
return res.status(400).json({ message: "Invalid Credentials" });
}
// Compare Password
console.log("Comparing password with bcrypt");
const match = await bcrypt.compare(req.body.password,user.password);
console.log("password compared");
console.log(match);
if (match == false) {
return res.status(400).json({ message: "Invalid Credentials" });
}
console.log("Password Matched");
// Generate Token
console.log("Generating Token........");
const token = user.generatetoken();
// Response
console.log("Sending Response........");
res.cookie("access-token",token).status(200).send(returnUserDoc(user));
} catch (error) {
console.log("Error");
res.status(400).json({ message: "Error while loggin in",error: error });
}
});
// functions
const returnUserDoc = (userDoc) => {
return {
_id: userDoc._id,name: userDoc.name,email: userDoc.email,phone: userDoc.phone,};
};
module.exports = router;
控制台日志 -
listening on port 3001
Database Connected
Finding User........
Comparing password with bcrypt
Error
我发现代码在 const match = await bcrypt.compare(req.body.password,user.password);
这一行之前成功执行
在 console.log(error.message);
我收到了这个 -
Error: data and hash arguments required
at Object.compare (D:\CovidHelpers\CovidHelpers\node_modules\bcrypt\bcrypt.js:208:17)
at D:\CovidHelpers\CovidHelpers\node_modules\bcrypt\promises.js:29:12
at new Promise (<anonymous>)
at Object.module.exports.promise (D:\CovidHelpers\CovidHelpers\node_modules\bcrypt\promises.js:20:12)
at Object.compare (D:\CovidHelpers\CovidHelpers\node_modules\bcrypt\bcrypt.js:204:25)
at D:\CovidHelpers\CovidHelpers\server\routes\api\users.js:60:32
at processticksAndRejections (internal/process/task_queues.js:93:5)
data and hash arguments required
请帮我解决这个问题:) 谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)