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

POST Requests in REST API

POST is an HTTP method commonly used to submit data to a server and create a new resource through a REST API.

For example, when a user registers on a website, submits a form, or adds a new product, the client can send a POST request containing the required data. The server validates the data, processes it, and returns an appropriate response.

In Node.js and Express.js, we can create POST endpoints using app.post(). JSON request bodies can be parsed using the built-in express.json() middleware.

1. What Is a POST Request?

A POST request submits data to a server for processing. It is commonly used to create a new resource in a REST API.

Examples include:

  • Creating a new user account.
  • Adding a new product to a product collection.
  • Submitting an order.
  • Sending form data to a server.
HTTP Request
POST /api/products
Content-Type: application/json

{
    "name": "Laptop",
    "price": 55000
}

In this request, the client sends a product name and price in the request body. The server can validate the data and create a product if the information is valid.

Remember: POST is commonly used to create resources, but its exact behavior depends on the API design. Unlike GET, POST is not generally considered a safe or idempotent HTTP method.

2. How a POST Request Works

The client sends data to a POST endpoint. Express parses the request body, the route handler validates and processes the data, and the server returns a response.

Step 1: Client

Submits product information

↓
Step 2: POST Request

POST /api/products

↓
Step 3: JSON Middleware

Parses the JSON request body

↓
Step 4: Route Handler

Validates and processes the submitted data

↓
Step 5: API Response

Returns the created resource and status code

The middleware must be registered before the route that uses the parsed request body. Otherwise, req.body may not contain the expected JSON data.

3. Creating a Simple POST API

Let us create a POST endpoint that accepts a product name and price and adds the product to an in-memory array.

Step 1: Create app.js

JavaScript
const express = require('express');

const app = express();

// Parse incoming JSON request bodies
app.use(express.json());

const products = [];
let nextId = 1;

// POST endpoint
app.post('/api/products', (req, res) => {
    const { name, price } = req.body;

    if (
        typeof name !== 'string' ||
        name.trim() === '' ||
        typeof price !== 'number' ||
        !Number.isFinite(price) ||
        price <= 0
    ) {
        return res.status(400).json({
            message: 'Valid name and positive price are required'
        });
    }

    const product = {
        id: nextId++,
        name: name.trim(),
        price
    };

    products.push(product);

    res.status(201).json({
        message: 'Product created successfully',
        product
    });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Step 2: Install Express.js

Terminal
npm init -y
npm install express

Step 3: Run the application

Terminal
node app.js

Expected terminal output:

Output
Server running on port 3000

The array stores products only while the server process is running. Restarting the application clears this in-memory data.

4. Sending a POST Request Using Postman

Postman is a tool used to send HTTP requests and inspect API responses. We can use it to test a POST endpoint.

Step 1: Select the HTTP method

Open Postman and select POST from the HTTP method dropdown.

Step 2: Enter the endpoint URL

http://localhost:3000/api/products

Step 3: Select the request body

  1. Open the Body tab.
  2. Select raw.
  3. Choose JSON as the format.
  4. Enter the following JSON data.
JSON Request Body
{
    "name": "Laptop",
    "price": 55000
}

Step 4: Click Send

If the server receives valid data, it creates a product and returns a response with HTTP status code 201.

Expected response:

JSON Response
{
    "message": "Product created successfully",
    "product": {
        "id": 1,
        "name": "Laptop",
        "price": 55000
    }
}
Remember: Set the request content type to application/json. Postman's raw JSON body option normally configures this header automatically.

5. Understanding req.body

In Express.js, req.body contains data parsed from the incoming request body when the appropriate body-parsing middleware is registered.

Consider this request body:

JSON
{
    "name": "Keyboard",
    "price": 1500
}

This code reads the submitted properties:

JavaScript
const { name, price } = req.body;

console.log(name);
console.log(price);

Example terminal output:

Output
Keyboard
1500

The destructuring syntax extracts the name and price properties from the request body.

Important: Request body values are user-controlled. Always validate the expected types, required fields, and acceptable values before processing or saving them.

6. Diagram 2: Request Body to API Response

This diagram shows how the submitted JSON data is processed before the server returns a response.

JSON Request Body

Name and price are submitted

↓
express.json()

Parses the JSON body into req.body

↓
Validation

Checks name and price

↓
Valid Data
↓
Create Product
↓
HTTP 201 Created
Invalid Data
↓
Reject Request
↓
HTTP 400 Bad Request

The application should create the resource only after the submitted data passes validation. If the data is invalid, it should return a suitable error response.

7. POST Request With Invalid Data

A REST API should not blindly accept all submitted values. Let us send invalid product data to our example endpoint.

Example request body:

JSON
{
    "name": "",
    "price": -100
}

The example API checks whether the name is a non-empty string and whether the price is a positive finite number. This request fails those checks.

Expected response:

JSON Response
{
    "message": "Valid name and positive price are required"
}

The API returns HTTP 400 Bad Request and does not add a product for this invalid request.

8. Common HTTP Status Codes for POST Requests

Status Code Meaning Typical Use
201 Created A new resource was created successfully. Product creation succeeded.
200 OK The request succeeded. A POST operation completed without using 201.
400 Bad Request The request data is invalid. A required field is missing or a value is invalid.
401 Unauthorized Authentication credentials are missing or invalid. The endpoint requires authentication.
500 Internal Server Error An unexpected server-side error occurred. An internal operation fails unexpectedly.

9. Best Practices for POST APIs

  • Use POST when submitting data for processing or resource creation.
  • Register express.json() before routes that read JSON request bodies.
  • Validate incoming data on the server.
  • Return HTTP 201 when a resource is successfully created.
  • Do not trust values received from the client.
  • Use a database when created resources must persist.
  • Do not expose internal errors or sensitive information in responses.
  • Use authentication and authorization where the operation requires them.

Important Points to Remember

  • POST is commonly used to submit data and create resources.
  • Use app.post() to define a POST endpoint in Express.js.
  • Use express.json() to parse JSON request bodies.
  • Access parsed body data through req.body.
  • Validate incoming data before creating a resource.
  • Use HTTP 201 when a resource is successfully created.
  • Use HTTP 400 when the submitted data is invalid.
  • In-memory data is temporary and is not a substitute for database storage.

Summary

POST is an HTTP method commonly used to submit data to a REST API and create resources. Express.js provides app.post() to define POST endpoints, while express.json() parses JSON request bodies.

By validating request data, returning suitable status codes, and storing resources appropriately, we can build POST endpoints that behave reliably and securely.