Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Accepting JSON using Node.js


Different web server systems accept data posted by a client in different ways. That being said, in most cases, you read the data piecewise as it comes in from the client and once the POST request finishes, process it as a batch. Here's how to do it with Node.js.

How to do it...

In our case, we accept JSON submitted from the client via HTTP POST requests. To do this, we need to read the data from the client, aggregate it in a string, and when all of the data arrives at the server, convert the data from a JSON string to a JavaScript object. In json-encoder, js, we modify it to read as the following:

 // … beginning of script is the same as in the introduction
    if (req.method == 'POST') {
      console.log('POST');
      var body = '';
      req.on('data', function(data) {
        body += data;
      });
      req.on('end', function() {     
      var json = JSON.parse(body);
      json.result = 'OK';
      res.writeHead(200, 
        {'Content-Type': 'application...