我对 MERN 堆栈开发真的很陌生。我在使用 bcrypt 时遇到了这个问题,我似乎无法让代码工作。这是代码。请帮忙。我正在尝试使用 bcrypt 加密我的密码
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;
const userSchema = new Schema({
name: String,
email: String,
phoneNumber: Number,
username: String,
password: String,
googleId: String,
credits: {type: Number, default: 0}
});
// this creates an instance of an object to be sent to the database
mongoose.model('users', userSchema);
userSchema.pre('save', function(next){
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt){
if(err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash){
if(err) return next(err);
user.password = hash;
next();
});
});
});
包 json 如下
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "8.8.1",
"npm": "5.0.3"
},
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "npm run start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"author": "David Mbwana",
"license": "ISC",
"dependencies": {
"axios": "^0.17.1",
"bcrypt": "^1.0.3",
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.2",
"concurrently": "^3.5.1",
"connect-flash": "^0.1.1",
"cookie-session": "^2.0.0-beta.3",
"express": "^4.16.2",
"express-validator": "^4.3.0",
"mongoose": "^4.13.6",
"nodemon": "^1.12.5",
"passport": "^0.4.0",
"passport-google-oauth20": "^1.0.0",
"passport-http": "^0.3.0",
"passport-local": "^1.0.0",
"path": "^0.12.7",
"redux-thunk": "^2.2.0",
"stripe": "^5.4.0"
}
}
密码仍在未经加密的情况下保存在数据库中。