在Postman中,我使用'POST'方法和url:http: // localhost: 7777 / register
,同时选择Body
和row
并粘贴对象{name: 'Martin}
。为什么在[" You must supply a name! "," That Email is not valid! "," Password Cannot be Blank! "," Confirmed Password cannot be
blank "," Oops! Your passwords do not match "]
中返回You must supply a name!"
,因为我在身体上给了我名字?此外,它的状态为500Internal Server Error
。
路由:index.js
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
router.get('/register', userController.registerForm);
router.post('/register',
userController.validateRegister,
userController.register
);
module.exports = router;
模型:User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const validator = require('validator');
const passportLocalMongoose = require('passport-local-mongoose');
const mongodbErrorHandler = require('mongoose-mongodb-errors');
const userSchema = new Schema ({
name: {
type: String,
trim: true,
required: 'Please supply a name'
},
email: {
type: String,
unique: true,
lowercase: true,
trim: true,
validate: [validator.isEmail, 'Invalid Email address'],
required: 'Please supply an email address'
}
})
userSchema.plugin(passportLocalMongoose, {usernameField: 'email'});
userSchema.plugin(mongodbErrorHandler);
module.exports = mongoose.model('User', userSchema);
控制器:userController.js
const mongoose = require('mongoose');
const User = mongoose.model('User');
const {promisify} = require("es6-promisify");
exports.registerForm = (req, res) => {
res.json('res');
};
exports.validateRegister = (req, res, next) => {
req.sanitizeBody('name');
req.checkBody('name', 'You must supply a name!').notEmpty();
req.checkBody('email', 'That Email is not valid!').isEmail();
req.sanitizeBody('email').normalizeEmail({
remove_dots: false,
remove_extension: false,
gmail_remove_subaddress: false
});
req.checkBody('password', 'Password Cannot be Blank!').notEmpty();
req.checkBody('password-confirm', 'Confirmed Password cannot be blank!').notEmpty();
req.checkBody('password-confirm', 'Oops! Your passwords do not match').equals(req.body.password);
const errors = req.validationErrors();
if (errors) {
res.send('error', errors.map(err => err.msg));
return; // stop the fn from running
}
next(); // there were no errors!
};
exports.register = async (req, res, next) => {
const user = new User({ email: req.body.email, name: req.body.name });
const register = promisify(User.register, User);
await register(user, req.body.password);
next(); // pass to authController.login
};
}
答案 0 :(得分:1)
您可能没有安装正确的正文解析器。例如,如果要处理JSON,请将其添加到快速应用程序设置中:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
// ...
app.use(bodyParser.json());
没有正文解析器,req.body
将不会按您期望的那样填充。
您还需要确保将Content-Type
标头设置为application/json
,以便您的服务器知道正文包含JSON。