Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Bad Request - node js ajax post

Bad Request - node js ajax post


I'm using express 3.0 and Node v0.11.0. I have a button which submits a form and I'm using ajax to post that data as a JSON object to my node server.
The client code is:

$('#contact').submit(function(e) {
console.log('submit called');
var formData = JSON.stringify($('form').serializeObject());

    url: "http://localhost:3000/savedata/",
    type: "POST",
    dataType: 'json',
    data: {objectData: formData},
    contentType: "application/json",
    complete: function() {
      console.log('process complete');
    success: function(data) {
      console.log('process sucess');
    error: function() {
      console.log('process error');
return false;

Then on my server:

var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public', {maxAge: 86400000}));
app.engine('.jade', require('jade').__express);'/savedata', function(req, res) {
  console.log('savedata called');
  //var resultObject = JSON.parse(req.body.objectData);

The problem that I'm facing is that when I use the express.bodyParser() middleware, I get a:

Error: Bad Request
at next (/home/captain/data/lemontreecakes/node_modules/express/node_modules/connect/lib/proto.js:125:13)
at /home/captain/data/lemontreecakes/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:54:23
at IncomingMessage. (/home/captain/data/lemontreecakes/node_modules/express/node_modules/connect/lib/middleware/json.js:74:60)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:883:14
at process._tickCallback (node.js:415:13)

This is the console output in my browser:

submit called load.js:33
{"name":"tes","email":"[email protected]"} load.js:36
POST http://localhost:3000/savedata/ 400 (Bad Request) jquery-1.9.1.min.js:5
process error load.js:54
process complete

So I know that I'm submitting data to my server. If I remove the body parser middle ware from node server, then I get

savedata called
TypeError: Cannot read property 'objectData' of undefined

I'm thinking that I'm not sending JSON data properly to the server. Any hints will be appreciated.

Problem courtesy of: Nilath


I'm not completely sure if this solves the problem but try this:

    data: JSON.stringify({ "objectData": formData}),
Solution courtesy of: Friederike


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Bad Request - node js ajax post


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription