lawx
lawx

Reputation: 388

Ajax POST to nodejs gives blank object

I am trying to successfully ping an object back and forth from the browser to a nodejs server via AJAX POST. However, I am having no luck, as the middleman from browser to server interprets the object as blank ( {} ). Does anybody know what I'm doing wrong?

Client:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/save");
xhr.onload = function(){
    console.log(xhr.responseText); //See what the server ponged
}
xhr.send({"foo": "bar"}); //Ping the object

Server:

var express = require('express');
var app = express();

app.configure(function() {
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.static(__dirname + '/public'));
  app.use(app.router);
});
app.configure('development', function() {
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function() {
  app.use(express.errorHandler());
});

app.post('/save', function(req, res){  //When server receives ping
    res.send(req.body);    // Pong the object back
});

var port = process.env.PORT || 3000;

var server = app.listen(port);

Thanks

Upvotes: 0

Views: 289

Answers (1)

azero0
azero0

Reputation: 2310

I know this is kind of hacky but works:

do this on your client side:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/save");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.onload = function(){
    console.log(JSON.parse(xhr.responseText)); //See what the server ponged
}
xhr.send('{"foo":"bar"}');

and on the server side send this:

res.send(Object.keys(req.body));

kind of hacky but worked for me :)

hope this helps you :)

Upvotes: 1

Related Questions