9

I am sending a credentials JSON object with the following request to node.js:

credentials = new Object();
credentials.username = username;
credentials.password = password;

$.ajax({
    type: 'POST',
    url: 'door.validate',
    data: credentials,
    dataType: 'json',
    complete: function(validationResponse) {
        ...
    }
});

On the server side i would like to load the submitted credentials into a JSON object to use it further on..

However, I don't know how to get the JSON out of the req object...

http.createServer(
    function (req, res) {
         // How do i acess the JSON
         // credentials object here?
    }
).listen(80);

(i have a dispatcher in my function(req, res) passing the req further on to controllers, so i would not like to use the .on('data', ...) function)

ndrizza
  • 3,285
  • 6
  • 27
  • 41

2 Answers2

17

At the server side you will receive the jQuery data as request parameters, not JSON. If you send data in JSON format, you will receive JSON and will need to parse it. Something like:

$.ajax({
    type: 'GET',
    url: 'door.validate',
    data: {
        jsonData: "{ \"foo\": \"bar\", \"foo2\": 3 }"
        // or jsonData: JSON.stringify(credentials)   (newest browsers only)
    },
    dataType: 'json',
    complete: function(validationResponse) {
        ...
    }
});

At server side you will do:

var url = require( "url" );
var queryString = require( "querystring" );

http.createServer(
    function (req, res) {

        // parses the request url
        var theUrl = url.parse( req.url );

        // gets the query part of the URL and parses it creating an object
        var queryObj = queryString.parse( theUrl.query );

        // queryObj will contain the data of the query as an object
        // and jsonData will be a property of it
        // so, using JSON.parse will parse the jsonData to create an object
        var obj = JSON.parse( queryObj.jsonData );

        // as the object is created, the live below will print "bar"
        console.log( obj.foo );

    }
).listen(80);

Note that this will work with GET. To get the POST data, take a look here: How do you extract POST data in Node.js?

To serialize your object to JSON and set the value in jsonData, you can use JSON.stringify(credentials) (in newest browsers) or JSON-js. Examples here: Serializing to JSON in jQuery

Community
  • 1
  • 1
davidbuzatto
  • 9,207
  • 1
  • 43
  • 50
  • 1
    Note that it might work in GET at some point. If the serialized data sent to the GET method gets too big, it might get truncated resulting in invalid json on the server side. – Loïc Faure-Lacroix May 18 '13 at 23:05
-5

Console.log the req

http.createServer(
    function (req, res) {

    console.log(req); // will output the contents of the req

    }
).listen(80);

The post data will be there somewhere if it was successfully sent.

jamjam
  • 3,171
  • 7
  • 34
  • 39