node.js parse JSON of request


Question

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)

1
7
8/16/2012 8:17:01 PM

Accepted Answer

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

16
5/23/2017 12:17:00 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon