js并处于学习阶段。我试图通过使用mongodb将新用户保存到数据库中来创建新用户。但是,当我尝试使用POSTMAN发布数据时,出现以下错误:
无法得到任何回应。连接到http://localhost:3000/create-user时出错
Nodemon也崩溃,显示[nodemon]应用程序崩溃-等待文件更改,然后再启动...
我手动运行该文件并进行了检查,但是当我尝试发布数据时,连接丢失并终止。
以下是server.js文件:
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
var User = require('./models/user');
const app = express();
mongoose.connect('mongodb://test:check123@ds211694.mlab.com:11694/parpet', { useNewUrlParser: true }, (err) => {
if(err) {
console.log(err);
} else {
console.log('Connected Successfully');
}
})
// Middleware for log data
app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.post('/create-user', (req, res) => {
var user = new User();
user.profile.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
user.save(function (err) {
console.log('checking.....');
if(err) {
console.log('Error');
} else {
res.json('Successfully created a new user');
}
});
});
const port = process.env.PORT || 3000;
app.listen(port, (err) => {
if(err) throw err;
console.log(`Server listening on port ${port}`);
});
模型文件是
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
var Schema = mongoose.Schema;
/* Creating User Schema */
var UserSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String,
profile: {
name: {
type: String,
default: ''
},
picture: {
type: String,
default: ''
}
},
address: String,
history: [{
date: Date,
paid: {
type: Number,
default: 0
},
// item:
}]
});
/* Hash the password */
UserSchema.pre('save', function (next) {
var user = this;
if(!user.isModified('password')) {
return next();
}
bcrypt.genSalt(10, function (err, salt) {
if(err) return next(err);
bcrypt.hash(user.password, salt, null, function (err, hash) {
if(err) return next(err);
user.password = hash;
next();
});
});
});
/* Comparing typed password with that in DB */
UserSchema.methods.comparePassword = function (password) {
return bcrypt.compareSync(password, this.password);
}
module.exports = mongoose.model('User', UserSchema);
我尝试按照其他stackoverflow问题中的说明禁用ssl连接,但这没有帮助。
所以有人可以帮我解决这个问题。这真的很有帮助。
node --version = v8.9.3
npm --version = 6.4.1
nodemon --version = 1.17.5
express --version = 4.16.0
谢谢
最佳答案
看来此对bcrypt的调用正在悄然崩溃:
bcrypt.hash(user.password, salt, null, function (err, hash) {
我不确定
null
参数的来源。如果删除它:bcrypt.hash(user.password, salt, function (err, hash) {
它不再崩溃,并且不返回任何错误。