我尝试制作注册表并保存到数据库(通过mLab云数据库),但是在提交表单后,服务器无法获取数据,也没有响应。我是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>
的usermodel
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);
答案 0 :(得分:0)
您在使用app.post
使用方法=&#34;发布&#34;这样你就可以从body.property
获得<form action="userSignUp" method="post">