我有一个mongolab(mlab)
帐户。我正在尝试使用Chrome浏览器中的postman
加载项为用户发布数据。我总是得到错误。我无法发布数据。我尝试过其他不同的方式。但没有运气。
是否有人帮我解决这个问题?
这是我的api.js
:
var
User = require('../models/user'),
config = require('../../config'),
secretKey = config.secretKey;
module.exports = function( app, express ) {
var api = express.Router();
api.post('/signup', function (req, res) {
var user = new User({
name:req.body.name,
username:req.body.username,
password:req.body.password
});
user.save(function(err){
if(err){
res.send(err);
return;
}
res.json({message:'User has been Created!'});
});
});
api.get('/users', function(req, res) {
User.find({}, function( req, users){
if(err) {
res.send(err);
return;
}
res.json(users);
})
});
return api;
}
config.js
:
module.exports = {
"database":"mongodb://xxx:xxxx@ds015700.mlab.com:15700/arifstory",
"port" : process.env.PORT || 3000,
"secretKey" : "YourSecretKey"
}
user.js
:
var
mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
name : String,
userName:{ type:String, required:true, index : { unique: true }},
password : { type:String, required : true, select : false }
});
UserSchema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) return next();
bcrypt.hash( user.password, null, null, function(err, hash) {
if(err) return next(err);
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function( password ) {
var user = this;
return bcrypt.compareSync(password, user.password);
}
module.exports = mongoose.model('User', UserSchema);
我真的无法理解这里的问题。请任何人帮助我?
错误
{
"message": "User validation failed",
"name": "ValidationError",
"errors": {
"userName": {
"message": "Path `userName` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "userName"
},
"kind": "required",
"path": "userName"
},
"password": {
"message": "Path `password` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "password"
},
"kind": "required",
"path": "password"
}
}
}
答案 0 :(得分:0)
从chrome发送的数据可能未定义。
在api.js文件中的user.save函数上面包含以下2行,在控制台中打印: 的console.log(req.body.username); 的console.log(req.body.password);
如果显示为未定义,请务必检查" x-www-form-urlencoded"在"身体"在Postman中,并提供用户名和密码。