limoragni
limoragni

Reputation: 2776

Make AJAX request using mootools and node.js with expressjs

I'm trying establish an AJAX connection on node 0.10.3 using mootools. My code is:

Client

var ajax = new Request({
url: '/register',
method: 'post',
onSuccess: function(responseText){
    console.log(responseText);
}
 })

 var json = {data:'data'};
 ajax.send(JSON.stringify(json));
 //ajax.send(json);

Server

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

app.use(express.static(__dirname + '/public'));

app.listen(1344);

app.post('/register', function(req,res){
     //Auth.register()
     console.log(req.body);
     res.contentType('json');
     res.send({ some: JSON.stringify({response:'json'}) })
})

The connection is working Ok. On the client I get the response. So the console.log(responseText) inside the OnSucces method is printing the correct value.

But on the server side, the console.log(req.body) is undefined.

I have a few doubts here. Does mootools converts the javascript object to a json string? Is it necessary to convert de object at all? What is the correct way of sending information trough AJAX to node? Is this ajax.send(JSON.stringify(json)); OK? Or is it like this ajax.send(json);?

Do I need to specify the headers to be json?

Apart for solving the particular problem, it would be nice some article, o some feedback to definitely clarify this concepts around node.js.

EDIT

I'm going to post the correct code, for those who are facing a similar problem. Noah was right about the parser, but there is another detail, the parser is expecting for the key data. Luckily I was using data as example!

Client

var ajax = new Request({
   url: '/register',
   method: 'post',
   onSuccess: function(responseText){
       console.log(responseText); //Logs "some": "{\"response\":\"json\"}"
   }
})
ajax.send({data:{ok:'OK'}});

Server

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

app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.listen(1344);

app.post('/register', function(req,res){
    console.log(req.body); //logs {ok:'OK'}
    res.contentType('json');
    res.send({ some: JSON.stringify({response:'json'}) })
})

Upvotes: 0

Views: 318

Answers (1)

Noah
Noah

Reputation: 34313

In the code you posted you are missing the bodyParser middleware app.use(express.bodyParser().

After you add the bodyParser middleware you will be able to access req.body

var express = require('express');
var app = express();
app.use(express.bodyParser()
app.use(express.static(__dirname + '/public'));
app.use(app.router)

Upvotes: 3

Related Questions