【发布时间】:2017-06-30 12:23:31
【问题描述】:
我尝试制作注册表并保存到数据库(通过mLab cloud db),但是在提交表单后,服务器无法获取数据并且也没有响应。我是MEAN Stack的新手,如果我犯了任何愚蠢的错误,请告知。 非常感谢。
controller.js
const bodyparser = require('body-parser');
const userModel = require('../model/userModel');app.use(bodyparser.urlencoded({extended:true}));
//create acc
app.post('/userSignUp', function(req, res){
if (!req.body) return res.sendStatus(404);
var newUser = new userModel({
username: req.body.username,
password: req.body.password
});
//save user to db
newUser.save(function(err){
if (err) throw err;
// fetch user and test password verification
userModel.findOne({username:req.body.username}, function(err, user){
if (err) throw err;
// test a matching password
user.comparePassword(req.body.password, function(err, isMatch){
if (err) throw err;
console.log(req.body.password, isMatch);
res.render('/index.ejs');
});
});
});});
注册表单
<!-- Sign up form -->
<div id="signup_form" style="width:50%; margin:0 auto;">
<h1>Sign up</h1>
<form action="userSignUp" method="get">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<span>
<input type="checkbox" name="checkbox">
<label for="checkbox">remember</label>
</span>
<input type="submit" value="Sign Up">
</form>
</div>
用户模型
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true }
});
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
【问题讨论】:
-
您能添加您的
../model/userModel.js文件吗? -
它会抛出任何错误吗?
-
顺便说一句,你不应该发回
404(意思是“未找到”),而是400(“错误请求”) -
没有错误被抛出...
标签: node.js express mongoose mean-stack