
- Home
-
HTML
HTML Introduction HTML Tags HTML Elements HTML Attributes HTML Heading HTML Paragraph HTML Formatting HTML Quotations HTML Comments HTML Styles HTML Color HTML CSS HTML Images HTML Favicon HTML Links HTML DIV HTML Tables HTML Table Size HTML Table Head Table Padding & Spacing Table colspan rowspsn HTML Table Styling HTML Colgroup HTML List HTML Block & Inline HTML Classes HTML Id HTML Iframes HTML Head HTML Layout HTML Semantic Elements HTML Style Guide HTML Forms HTML Form Attribute HTML Form Element HTML input type HTML Computer code HTML Entity HTML Symbol HTML Emojis HTML Charset HTML Input Form Attribute HTML URL Encoding
-
CSS
CSS Introduction CSS Syntax CSS Selector How To Add CSS CSS Comments CSS Colors CSS Background color CSS background-image CSS Borders CSS Margins CSS Height, Width and Max-width CSS Box Model CSS Outline CSS Text CSS Fonts CSS Icon CSS Links CSS Tables CSS Display CSS Maximum Width CSS Position z-index Property
- JavaScript
-
JQuery
What is jQuery? Benefits of using jQuery Include jQuery Selectors. Methods. The $ symbol and shorthand. Selecting elements Getting and setting content Adding and removing elements Modifying CSS and classes Binding and Unbinding events Common events: click, hover, focus, blur, etc Event delegation Using .on() for dynamic content Showing and hiding elements Fading elements in and out Sliding elements up and down .animate() Understanding AJAX .ajax() .load(), .get(), .post() Handling responses and errors. Parent Chlid Siblings Filtering Elements Using find Selecting form elements Getting form values Setting form values Form validation Handling form submissions jQuery plugins Sliders plugins $.each() $.trim() $.extend() Data attributes Debugging jQuery code
-
Bootstrap 4
What is Bootstrap Benefits of using Setting up Container Row and Column Grid Classes Breakpoints Offsetting Columns Column Ordering Basic Typography Text Alignment Text colors Backgrounds Display Font Size Utilities Buttons Navs and Navbar Forms Cards Alerts Badges Progress Bars Margin Padding Sizing Flexbox Dropdowns Modals Tooltips Popovers Collapse Carousel Images Tables Jumbotron Media Object
- Git
-
PHP
PHP Introduction PHP Installation PHP Syntax PHP Comments PHP Variable PHP Echo PHP Data Types PHP Strings PHP Constant PHP Maths PHP Number PHP Operators PHP if else & if else if PHP Switch PHP Loops PHP Functions PHP Array PHP OOps PHP Class & Object PHP Constructor PHP Destructor PHP Access Modfiers PHP Inheritance PHP Final Keyword PHP Class Constant PHP Abstract Class PHP Superglobals PHP Regular Expression PHP Interfaces PHP Static Method PHP Static Properties PHP Namespace PHP Iterable PHP Form Introduction PHP Form Validation PHP Complete Form PHP Date and Time PHP Include Files PHP - Files & I/O File Upload PHP Cookies PHP SESSION PHP Filters PHP Callback Functions PHP JSON PHP AND Exceptions PHP Connect database
-
MY SQL
SQL Introduction Syntax Select statement Select Distinct WHERE Clause Order By SQL AND Operator SQL OR Operator SQL NOT Operator SQL LIKE SQL IN SQL BETWEEN SQL INSERT INTO SQL NULL Values SQL UPDATE SQL DELETE SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause SQL MIN() and MAX() Functions SQL COUNT() Function SQL SUM() SQL AVG() SQL Aliases SQL JOIN SQL INNER JOIN SQL LEFT JOIN SQL RIGHT JOIN SQL FULL OUTER JOIN SQL Self Join SQL UNION SQL GROUP BY SQL HAVING SQL EXISTS SQL ANY and ALL SQL SELECT INTO SQL INSERT INTO SELECT SQL CASE SQL NULL Functions SQL Stored Procedures SQL Comments SQL Operators SQL CREATE DATABASE SQL DROP DATABASE SQL BACKUP DATABASE SQL CREATE TABLE SQL DROP TABLE SQL ALTER TABLE SQL Constraints SQL NOT NULL SQL UNIQUE Constraint SQL PRIMARY KEY SQL FOREIGN KEY SQL CHECK Constraint SQL CREATE INDEX SQL AUTO INCREMENT SQL Dates SQL Views SQL Injection SQL Hosting SQL Data Types
Understanding the http
Module in Node.js
The http
module in Node.js is a built-in module that allows you to create HTTP servers and handle HTTP requests and responses. It is fundamental for building web applications and services.
Key Features of the http
Module:
- Creating HTTP servers: The
http
module allows you to create a server that listens for incoming HTTP requests on a specific port. - Handling requests and responses: You can handle different HTTP methods (like GET, POST, etc.), process request data, and send responses back to clients.
Basic Example: Creating a Simple HTTP Server
Let's create a simple HTTP server using the http
module. This server will listen on port 3000 and respond with "Hello, World!" when accessed.
-
Step 1: Initialize a Node.js Project First, create a directory for your project and initialize it with npm:
mkdir my-http-server cd my-http-server npm init -y
-
Step 2: Create the Server File
Create a file named
server.js
:touch server.js
-
Step 3: Write the Server Code
In
server.js
, write the following code:// Import the http module const http = require('http'); // Create an HTTP server const server = http.createServer((req, res) => { // Set the response header res.writeHead(200, { 'Content-Type': 'text/plain' }); // Send a response to the client res.end('Hello, World!\n'); }); // The server listens on port 3000 server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
-
Step 4: Run the Server
Run your server using Node.js:
node server.js
You should see the following output in your terminal:
Server running at http://localhost:3000/
-
Step 5: Access the Server
Open your web browser and go to
http://localhost:3000/
. You should see the message "Hello, World!" displayed on the page.
Explanation of the Code:
require('http')
: This imports the built-inhttp
module.http.createServer(callback)
: This creates an HTTP server. Thecallback
function is called whenever a request is received. It has two parameters:req
(the request object) andres
(the response object).res.writeHead(200, { 'Content-Type': 'text/plain' })
: This sets the HTTP status code to 200 (OK) and the content type totext/plain
.res.end('Hello, World!\n')
: This sends the response body and closes the response.server.listen(3000, callback)
: This makes the server listen on port 3000. When the server starts, it runs the provided callback function, which logs a message to the console.
Understanding npm install http
If you try to install the http
module using npm install http
, it will not work as expected because the http
module is a core module in Node.js, meaning it is built into Node.js and doesn't need to be installed separately.
If you run:
npm install http
It will install a package named http
, but this is not the same as the core http
module in Node.js. The core http
module is always available without installation.
Advanced Example: Handling Different Routes
Let's expand the server to handle different routes.
-
Modify
server.js
to handle two different routes:const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to the Home Page!\n'); } else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('About Us Page\n'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found\n'); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
-
Run the server again:
node server.js
-
Test different routes:
- Go to
http://localhost:3000/
for the home page. - Go to
http://localhost:3000/about
for the about page. - Go to any other route, e.g.,
http://localhost:3000/contact
, and you’ll get a 404 error.
- Go to
This example demonstrates how to handle different routes and return different responses based on the URL requested.
Conclusion
The http
module is a powerful tool in Node.js that allows you to build and manage web servers. Understanding its basics, such as creating servers, handling requests, and managing responses, is essential for any Node.js developer. The key takeaway is that the http
module is built-in and does not require installation via npm.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.