user3782326 user3782326 - 2 months ago 10
Node.js Question

Cannot get value of the body from backbone post url to nodejs

I am learning backbone and nodejs, using the url
https://addyosmani.com/backbone-fundamentals/#talking-to-the-server

I am trying to save the data of the book, While submiting the form, the values saved in collection and the db using node. the

collection.create(formData)
is the code for create collection and post the data in node. While I am trying to post, the formData contains an value, But in node getting the body object is empty.

In the learning program the nodejs is lower version I am using the higher version(4.x)

View Code:

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);
}
});


And My server Code:

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);
});


My console while submit the output
In node

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


In 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


my whole project is here --
https://drive.google.com/open?id=0BzZNadB85XQVdjJPRE9ra2FpLWc
Thanks in advance

Answer

Use app.use(bodyParser.json()); in server.js file.