Reputation: 409
While making below ajax call, I am not seeing any post data in node server side.
$.ajax({
type: "POST",
url: window.location.origin + "/api/books",
data: {
title: "Javascript some good partd",
author: "Douglas crockford",
releaseDate: new Date(2013, 4, 2).getTime()
},
dataType: "json",
success: function(data) {
console.log(data);
}
});
After doing some search, I found out it could be because of body-parser configuration but unable to get it right. Please find below the node server configuration.
app.configure( function() {
app.use(bodyParser());
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, 'site')));
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
});
And API call is:
app.post('/api/books', function (req, res) {
console.log(req.body);
var book = new BookModel({
title: req.body.title,
author: req.body.author,
releaseDate: req.body.releaseDate
});
return book.save(function (err, response) {
if (!err) {
return res.send(book);
} else {
console.log(err);
}
});
});
req.body is logged as undefined. Can anyone please help on debugging the issue?
Upvotes: 0
Views: 33
Reputation: 144
Drop the app.configure function.
All the code inside of it can be left floating in that file.
My best guess would be that its not firing off that function.
I tend to use this code
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Upvotes: 1