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 = ...

Get JavaScript JSON Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.