我正在使用MEAN
应用,我已使用name,username,password
创建了一个帖子请求 - 我正在尝试使用postman
Chrome加载项对此进行测试。
但我总是收到错误,而不是发布我的数据。
我正在与db
这样连接:
mongoose.connect( 'mongodb://jbarif:root@ds147975.mlab.com:47975/family', function( err ) {
if( err ) console.log( err );
console.log( 'connection successful!' ); //getting consoled
} );
发布如下数据:
"use strict";
var User = require('../models/userModel');
module.exports = function( express, app ){
var openApi = express.Router();
openApi.post('/create', function( req, res ){
var user = new User();
var name = req.body.name;
var username = req.body.username;
var password = req.body.password;
console.log( name, username, password + '\n' + user );
user.save(function(err) {
if (err) {
// duplicate entry
if (err.code == 11000)
return res.json({ success: false, message: 'A user with that username already exists. '});
else
return res.send(err); //always getting this!
}
res.json({ message: 'User created!' });
});
});
//prefixing the open apis
app.use('/open', openApi);
return openApi;
}
这是来自postman
的错误:
{
"message": "User validation failed",
"name": "ValidationError",
"errors": {
"password": {
"message": "Path `password` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "password"
},
"kind": "required",
"path": "password"
},
"username": {
"message": "Path `username` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "username"
},
"kind": "required",
"path": "username"
}
}
}
据您所知,我的server.js
:
var
express = require('express'),
path = require('path'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
port = process.env.PORT || 8080,
mongoose = require('mongoose'),
openApi = require('./app/api/openApi'),
familyApi = require('./app/api/familyApi'),
app = express();
//app config;-
var base = app.use( express.static( __dirname + '/public') );
var reqest = app.use( morgan('dev') );
var jsonParse = app.use( bodyParser.json() );
var urlParse = app.use( bodyParser.urlencoded({extended:true}));
mongoose.connect( 'mongodb://jbarif:root@ds147975.mlab.com:47975/family', function( err ) {
if( err ) console.log( err );
console.log( 'connection successful!' );
} );
// mongoose.connect('mongodb://node:noder@ds013456.mlab.com:13456/practical');
//calling api from another files;
openApi( express, app );
familyApi( express, app );
app.get('/', function( req, res ) {
res.sendFile( path.join( __dirname + '/public/app/views/index.html') );
});
app.get('*', function( req, res, next ) {
return res.status(404).json({success: false, message: 'Route \'' + req.url + '\' is invalid.'});
});
app.listen( port );
console.log('app is listening at', port );
答案 0 :(得分:1)
Mongoose验证失败,因为用户对象中没有任何内容。
将其更改为:
var userData = {name: req.body.name, username: req.body.username, password:req.body.password};
var user = new User(userData);