我正在使用url学习主干和nodejs https://addyosmani.com/backbone-fundamentals/#talking-to-the-server
我正在尝试保存书籍的数据,在提交表单时,保存在集合中的值和使用节点的数据库。 collection.create(formData)
是创建集合的代码,并在节点中发布数据。当我试图发布时,formData包含一个值,但在节点中获取body对象是空的。
在学习程序中,nodejs是较低版本我正在使用较高版本(4.x)
查看代码:
var app = app || {};
app.LibraryView = Backbone.View.extend({
el: '#books',
initialize: function(){
this.Collection = new app.Library(); // UPDATED
this.Collection.fetch({reset: true});
this.render();
this.listenTo( this.Collection, 'add', this.renderBook );
this.listenTo( this.Collection, 'reset', this.render ); // NEW
},
events: {
'click #add': 'addBook'
},
render: function(){
this.Collection.each(function(item){
this.renderBook(item);
},this);
},
renderBook: function(item){
var bookView = new app.BookView({
model: item
});
this.$el.append(bookView.render().el);
},
addBook: function(e){
e.preventDefault();
var formData = {};
$( '#addBook div' ).children( 'input' ).each( function( i, el ) {
if( $( el ).val() !== '' )
{
if(el.id === 'keywords' ){
formData[ el.id ] = [];
_.each($(el).val().split(' '), function(keyword){
formData[ el.id ].push({keyword : keyword});
});
} else if( el.id === 'releaseDate'){
formData[ el.id ] = $( "#releaseDate" ).datepicker('getDate');
} else {
formData[ el.id ] = $( el ).val();
}
}
$( el ).val('');
});
console.log('sending FormData :', formData);
this.Collection.create(formData);
}
});
我的服务器代码:
var app_root = __dirname,
express = require('express'),
path = require('path'),
mongoose = require('mongoose');var app = express();
mongoose.connect('mongodb://admin:password@ds025263.mlab.com:25263/myworks');
var Keywords = new mongoose.Schema({
keyword: String
});
var Book = new mongoose.Schema({
title: String,
author: String,
releaseDate: String,
keywords : [Keywords]
});
var BookModel = mongoose.model('Book', Book);
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(methodOverride());
app.use(express.static(path.join(app_root,'./','site')));
app.get('/api',function(req, res){
res.send('Library Api is running...');
});
app.get('/api/books',function(req,res){
return BookModel.find(function(err,books){
if(!err){
console.log('total : ',books);
return res.send(books);
}else{
return console.log(err);
}
});
});
app.post( '/api/books', function( request, response ) {
var title = request.body;
var book = new BookModel({
title: request.body.title,
author: request.body.author,
releaseDate: request.body.releaseDate,
keywords: request.body.keywords // NEW
});
console.log('before -- save : ', title);
console.log('before -- save : ', request.body.author);
console.log('before -- save : ', request.body.releaseDate);
console.log('before -- save : ', request.body.keywords);
console.log('before -- save : ', book);
console.log('before -- save : ', book);
book.save( function( err ) {
if( !err ) {
console.log( 'created' );
return response.send( book );
} else {
return console.log( ' after - save : ',err );
}
});
});
app.get('/api/books:id',function(req,res){
return BookModel.findById(req.params.id, function(err, book){
if(!err){
return res.send(book);
}
else{
return console.log(err);
}
});
});
app.put( '/api/books/:id', function( request, response ) {
console.log( 'Updating book ' + request.body.title );
return BookModel.findById( request.params.id, function( err, book ) {
book.title = request.body.title;
book.author = request.body.author;
book.releaseDate = request.body.releaseDate;
book.keywords = request.body.keywords; // NEW
return book.save( function( err ) {
if( !err ) {
console.log( 'book updated' );
return response.send( book );
} else {
console.log( err );
}
});
});
});
app.delete('/api/books/:id', function(req, res){
console.log('Deleting book with Id : ', req.params.id);
return BookModel.findById(req.params.id, function(err, book){
if(!err){
console.log('Book Removed');
return res.send(book);
}else{
console.log(err);
}
});
});
var port = 3000;
app.listen(port, function(){
console.log('Server listening on the port %d in %s mode', port, app.settings.env);
});
提交输出时我的控制台 在节点
中before -- save : {}
before -- save : undefined
before -- save : undefined
before -- save : undefined
before -- save : { _id: 57dfa0d7aa34452730647e29, keywords: [] }
before -- save : { _id: 57dfa0d7aa34452730647e29, keywords: [] }
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
在Backbone中
Sending FormData : Object {title: "sathish", author: "sathish", releaseDate: Thu Sep 01 2016 00:00:00 GMT+0530 (India Standard Time), keywords: Array[1]}author: "sathish"coverImage: "img/backbone.png"keywords: Array[1]releaseDate: Thu Sep 01 2016 00:00:00 GMT+0530 (India Standard Time)title: "sathish"__proto__: Object
我的整个项目都在这里 - https://drive.google.com/open?id=0BzZNadB85XQVdjJPRE9ra2FpLWc 提前致谢
答案 0 :(得分:1)
在server.js文件中使用app.use(bodyParser.json());
。