我正在使用MEAN
应用程序,我已经与name,username,password
创建了一个post request -我正在尝试使用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 );
Mongoose验证失败,因为用户对象中没有任何内容。
改为:
var userData = {name: req.body.name, username: req.body.username, password:req.body.password};
var user = new User(userData);