Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Parsing JSON Body in Node.js

Parsing a JSON body is an important part of handling HTTP requests in Node.js. When a client sends JSON data to a server, the server receives that data as a stream of chunks. We need to collect the complete request body and convert the JSON text into a JavaScript object using JSON.parse().

In this lesson, we will learn how to receive JSON data using the built-in HTTP module, parse the request body, validate the received data, handle invalid JSON, and send a JSON response to the client.


1. What Does Parsing a JSON Body Mean?

Parsing a JSON body means converting JSON text received in an HTTP request into a JavaScript value that our application can use.

For example, Samadhan sends his name and course to the server. The server receives the following JSON data.

JSON Request Body
{
    "name": "Samadhan",
    "course": "Node.js"
}

After parsing the JSON, the server can access the values using student.name and student.course.

Client / Browser

Sends JSON request body

↓
Node.js HTTP Server

Receives request body chunks

↓
JSON.parse()

Converts JSON text into a JavaScript object

↓
HTTP Response

Returns the processed result as JSON

2. Understanding JSON.parse()

The JSON.parse() method converts a valid JSON string into a JavaScript value, such as an object or an array.

Syntax:

JavaScript
JSON.parse(jsonString);

Example:

JavaScript
const jsonData = '{"name":"Samadhan","course":"Node.js"}';

const student = JSON.parse(jsonData);

console.log(student.name);
console.log(student.course);

Output:

Terminal Output
Samadhan
Node.js

After parsing, student becomes a JavaScript object. We can access its properties using dot notation.

3. Receiving the HTTP Request Body

In Node.js, the built-in HTTP module provides the request object as a readable stream. The body may arrive in multiple chunks, so we collect those chunks until the end event occurs.

Example:

JavaScript
let body = '';

req.on('data', (chunk) => {
    body += chunk;
});

req.on('end', () => {
    console.log(body);
});

Explanation:

Code Meaning
let body = ''; Creates an empty string to collect incoming data.
req.on('data', ...) Runs whenever a body chunk is received.
body += chunk; Adds the received chunk to the body.
req.on('end', ...) Runs when the request body has finished arriving.

We should call JSON.parse(body) only after the complete request body has been received.

4. Creating a Server to Parse JSON

Now let us create a complete example. Samadhan sends student information to the server, and the server parses and validates the JSON before returning a response.

Step 1: Create a file named server.js.

server.js
const http = require('http');

const server = http.createServer((req, res) => {

    if (req.method === 'POST' && req.url === '/students') {

        const contentType = req.headers['content-type'] || '';

        if (!contentType.toLowerCase().includes('application/json')) {
            res.writeHead(415, {
                'Content-Type': 'application/json; charset=utf-8'
            });

            res.end(JSON.stringify({
                message: 'Content-Type must be application/json'
            }));

            return;
        }

        let body = '';
        let bodySize = 0;
        const maxBodySize = 1024 * 1024;

        req.on('data', (chunk) => {
            bodySize += chunk.length;

            if (bodySize > maxBodySize) {
                res.writeHead(413, {
                    'Content-Type': 'application/json; charset=utf-8'
                });

                res.end(JSON.stringify({
                    message: 'Request body is too large'
                }));

                req.destroy();
                return;
            }

            body += chunk;
        });

        req.on('end', () => {
            if (res.writableEnded) {
                return;
            }

            try {
                const student = JSON.parse(body);

                if (
                    student === null ||
                    typeof student !== 'object' ||
                    Array.isArray(student)
                ) {
                    res.writeHead(400, {
                        'Content-Type': 'application/json; charset=utf-8'
                    });

                    res.end(JSON.stringify({
                        message: 'Expected a JSON object'
                    }));

                    return;
                }

                if (
                    typeof student.name !== 'string' ||
                    student.name.trim() === '' ||
                    typeof student.course !== 'string' ||
                    student.course.trim() === ''
                ) {
                    res.writeHead(400, {
                        'Content-Type': 'application/json; charset=utf-8'
                    });

                    res.end(JSON.stringify({
                        message: 'Name and course are required'
                    }));

                    return;
                }

                res.writeHead(201, {
                    'Content-Type': 'application/json; charset=utf-8'
                });

                res.end(JSON.stringify({
                    message: 'Student data received successfully',
                    student: {
                        name: student.name.trim(),
                        course: student.course.trim()
                    }
                }));

            } catch (error) {
                res.writeHead(400, {
                    'Content-Type': 'application/json; charset=utf-8'
                });

                res.end(JSON.stringify({
                    message: 'Invalid JSON format'
                }));
            }
        });

    } else {
        res.writeHead(404, {
            'Content-Type': 'application/json; charset=utf-8'
        });

        res.end(JSON.stringify({
            message: 'Route not found'
        }));
    }
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});

Step 2: Understand the important parts.

Code Purpose
http.createServer() Creates the HTTP server.
req.method Checks the HTTP request method.
req.url Checks the requested route.
req.on('data', ...) Collects incoming request body chunks.
JSON.parse(body) Converts JSON text into a JavaScript value.
try...catch Handles invalid JSON parsing errors.
JSON.stringify() Converts JavaScript data into JSON text for the response.
res.writeHead() Sets the HTTP status and response headers.
res.end() Sends the response and finishes it.

The example limits the body to 1 MB and checks that the received data is a JSON object containing non-empty name and course values. Production servers should also handle aborted requests and body limits carefully.

5. Running the Node.js Server

Open the terminal in the folder where you saved server.js.

Terminal
node server.js

Expected output:

Terminal Output
Server running at http://localhost:3000

The server is now listening on port 3000 and is ready to receive requests.

6. Sending JSON Data to the Server

We can use curl to send a POST request containing JSON data to the /students route.

Terminal
curl -X POST http://localhost:3000/students -H "Content-Type: application/json" -d "{\"name\":\"Samadhan\",\"course\":\"Node.js\"}"

The Content-Type: application/json header tells the server that the request body contains JSON data.

Expected JSON response:

JSON Response
{
    "message": "Student data received successfully",
    "student": {
        "name": "Samadhan",
        "course": "Node.js"
    }
}

The server returns HTTP status 201 Created when the request body is valid and the required fields are present.

7. Handling Invalid JSON

Suppose Pradnya sends invalid JSON with a missing quotation mark. In this situation, JSON.parse() throws an error. The catch block handles the error and returns a client-friendly response.

Example of invalid JSON:

Invalid JSON
{
    "name": "Pradnya,
    "course": "Node.js"
}

Expected response:

JSON Response
{
    "message": "Invalid JSON format"
}

The server returns HTTP status 400 Bad Request because the request body is not valid JSON.

8. JSON.parse() vs JSON.stringify()

These two methods perform opposite operations when exchanging JSON data.

Method Purpose Example
JSON.parse() Converts JSON text into a JavaScript value. JSON.parse(jsonData)
JSON.stringify() Converts a JavaScript value into JSON text. JSON.stringify(student)

Easy example:

JavaScript
const jsonData = '{"name":"Samadhan"}';

const student = JSON.parse(jsonData);

console.log(student.name);

const responseData = JSON.stringify(student);

console.log(responseData);

Output:

Terminal Output
Samadhan
{"name":"Samadhan"}

Remember: parse reads JSON text into a JavaScript value, while stringify converts a JavaScript value into JSON text.

9. Important HTTP Status Codes

Status Code Meaning When It Is Used
201 Created Request processed successfully. Valid student data was received.
400 Bad Request Invalid request data. JSON is malformed or required fields are missing.
404 Not Found Requested route does not exist. Client requests an unsupported URL.
413 Content Too Large Request body exceeds the size limit. Body is larger than the configured limit.
415 Unsupported Media Type Unsupported request content type. Request does not specify JSON content.

10. Common Mistakes to Avoid

  • Parsing before the body is complete: call JSON.parse() after the request's end event.
  • Ignoring invalid JSON: use try...catch around JSON.parse().
  • Not checking the content type: verify that the client sends JSON when the endpoint expects JSON.
  • Skipping validation: valid JSON does not automatically mean the data has the correct structure or required values.
  • Accepting unlimited body sizes: configure a reasonable request body limit.

11. Practice Tasks

Task 1: Parse Student JSON

  1. Create a file named server.js.
  2. Create a POST route named /students.
  3. Receive the request body using the data and end events.
  4. Convert the JSON text into a JavaScript object using JSON.parse().
  5. Display the student's name and course in the response.

Expected result: The server should return the parsed student details as JSON.

Task 2: Handle Invalid JSON

  1. Send valid JSON to the /students route.
  2. Send malformed JSON to the same route.
  3. Use try...catch to handle parsing errors.
  4. Return HTTP status 400 for invalid JSON.

Expected result: Valid JSON should be processed, while invalid JSON should receive an appropriate error response.

Summary

Parsing a JSON body allows a Node.js application to process structured data sent by a client. The HTTP request body is received as a stream, so the application collects the chunks and waits until the body is complete before calling JSON.parse().

We also learned to validate the parsed data, check the request content type, limit the body size, handle invalid JSON using try...catch, and send JSON responses using JSON.stringify(). These techniques are useful when building HTTP APIs at CIIT Training Institute.