0% found this document useful (0 votes)
27 views89 pages

Module 6 - Node JS - Up To Form Get Method

Uploaded by

r21921924
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views89 pages

Module 6 - Node JS - Up To Form Get Method

Uploaded by

r21921924
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

1

UBCA301L – Full Stack


Application Development
DR.BRINDHA.K
PROFESSOR GRADE 1
SCORE

Dr.Brindha.K 9/16/2025
2 MODULE 6 : NodeJS
Getting Started with Node.js
Using Events
Listeners
Timers and Callbacks in Node.Js
Handling data I/O in Node.js
Accessing the File System from Node.js
Implementing HTTP Services in Node.js

Dr.Brindha.K 9/16/2025
3 Traditional Web Server Model
 In the traditional web server model, each request is handled by a
dedicated thread from the thread pool.
 If no thread is available in the thread pool at any point of time then the
request waits till the next available thread.
 Dedicated thread executes a particular request and does not return to
thread pool until it completes the execution and returns a response.
4 Node.js Process model
 Node.js processes user requests differently when compared to a traditional
web server model.
 Node.js runs in a single process and the application code runs in a single
thread and thereby needs less resources than other platforms.
 All the user requests to your web application will be handled by a single
thread and all the I/O work or long running job is performed asynchronously
for a particular request.
 So, this single thread doesn't have to wait for the request to complete and is
free to handle the next request.
 When asynchronous I/O work completes then it processes the request
further and sends the response.
 An event loop is constantly watching for the events to be raised for an
asynchronous job and executing callback function when the job
completes.
5 Node.js Process model
 Node.js uses libev for the event loop which in turn uses internal C++ thread
pool to provide asynchronous I/O.
6 Example - Real time scenario
7 Differentiate between Traditional web
server and Node.js Server
 A common task for a web server can be to open a file on the server and return the content to the
client
 Traditional web server
 Sends the task to the computer's file system,
 Waits while the file system opens and reads the file
 Return the content to the client
 Ready to handle the next request.
 Node.js Server
 Sends the task to the computer file system.
 Ready to the handle the next request
 When the file system has opened and read the file, the server returns the content to the client.
 Node.js eliminates the waiting and simply continues with the next request.
 Node.js runs single threaded, non blocking, asynchronously programming which is very memory
efficient.
8 Node JS - Introduction
 Basically, Node.js is a run-time environment based on
JavaScript, that can be used as frontend and backend.
 Node.js platform, then it was created by the developer
Ryan Dahl in the year 2009.
 Considering the popularity of the Node.js development
on SimilarTech website, around 175k websites are
developed using the node.js.
 The highest number of Node.js websites are developed
in the United States followed by India and UK.
9 Node JS – Use cases
 Nodejs has gained immense popularity among developers for the fantastic
development of web applications.
 Node.js development is special for backend developers.
 Most of the Node js Development Company use the nodejs for
development is that it is an open-source, and community-loved engine.
 As we all know, Nodejs is a runtime built on the popular Chrome V8
JavaScript engine.
 Nodejs comes from the JavaScript family that allows the developers to use
the same programming on both the front-end and back-end.
 Node.js development is not only limited to web applications but also
includes the development in the microcontrollers, REST APIs, static file
servers, chatbots, queued I/O inputs, etc.
10 Node JS – Use cases
11 Top World famous companies using
Node.js
12 Important features of Node.js
 Node.js can generate dynamic page content.
 Node.js can create, open , read, write, delete and close
files on the server.
 Node.js can collect form data.
 Node.js can add, delete, modify data in your database.
13 Install Node.js on Windows
 Node.js development environment can be setup in Windows, Mac, Linux
and Solaris.
 Visit Node.js official web site https://nodejs.org. It will automatically detect
OS and display download link as per your Operating System.
 Download Node.js installer for windows.
14 Install Node.js on Windows

Click the button


15 Install Node.js on Windows

Download msi file


16 Install Node.js on Windows
 After you download the MSI, double-click on it to start the installation as shown
below.

 Click Next to read and accept the License Agreement and then click Install. It
will install Node.js quickly on your computer. Finally, click finish to complete the
installation.
17 Verify Installation
 Once you install Node.js on your computer, you can verify it by opening the
command prompt and typing node -v.
 If Node.js is installed successfully then it will display the version of the
Node.js installed on your machine, as shown below
18 Node.js Console/REPL
 Node.js comes with virtual environment called REPL (aka Node shell). REPL
stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple
Node.js/JavaScript code.
 To launch the REPL (Node shell), open command prompt (in Windows) or
terminal (in Mac or UNIX/Linux) and type node as shown below. It will
change the prompt to > in Windows and MAC.
19 Node.js Console/REPL
 . You can also define variables and perform some operation on them

 If you need to write multi line JavaScript expression or function then just
press Enter whenever you want to write something in the next line as a
continuation of your code.
20 Node.js Console/REPL
 You can execute an external JavaScript file by executing the node
fileName command.
 Example.js contains the following statement
 console.log("Welcome to Node JS beginners");
21 Node.js basics
 Node.js supports JavaScript. So, JavaScript syntax on Node.js is similar to
the browser's JavaScript syntax.
 JavaScript in Node.js supports loose typing like the browser's JavaScript.
Use var keyword to declare a variable of any type.
 Object literal syntax is same as browser's JavaScript.
 var obj = { authorName: 'Ryan Dahl', language: 'Node.js' }
 A function can have attributes and properties also. It can be treated like a
class in JavaScript.
 function Display(x) { console.log(x); } Display(100);
 Node.js includes an additional data type called Buffer (not available in
browser's JavaScript). Buffer is mainly used to store binary data, while
reading from a file or receiving packets over the network.
22 Node.js basics
 Each Node.js script runs in a process. It includes process object to get all
the information about the current process of Node.js application.
 The following example shows how to get process information in REPL
using process object.
23 Node.js Module
 Module in Node.js is a simple or complex functionality
organized in single or multiple JavaScript files which can
be reused throughout the Node.js application.
 Node.js includes three types of modules:
Core Modules
Local Modules
Third Party Modules
24 Core Modules
 Built-in modules of node. js that are part of nodejs and come with the Node. js
installation process are known as core modules.
 However, you need to import the core module first in order to use it in your
application.
 To load/include this module in our program, we use the require function.
Core Module Description
http http module includes classes, methods and events to create
Node.js http server.
url url module includes methods for URL resolution and parsing.
querystring querystring module includes methods to deal with query string.
path path module includes methods to deal with file paths.
fs fs module includes classes, methods, and events to work with file
I/O.
util util module includes utility functions useful for programmers.
25 Loading core modules
 In order to use Node.js core or NPM modules, you first need to import it
using require() function as shown below.
 var module = require('module_name');
 As per above syntax, specify the module name in the require() function. The
require() function will return an object, function, property or any other
JavaScript type, depending on what the specified module returns.
 var http = require('http');
 var server = http.createServer(function(req, res)
 { //write code here });
 server.listen(5000);
26 Node.js Local Module
 We can define modules locally as Local Module. It consists different
functions declared inside a JavaScript object and we reuse them
according to the requirement.
 We can also package it and distribute it using NPM.
 Local module must be written in a separate JavaScript file. In the separate
file, we can declare a JavaScript object with different properties and
methods.
27 Local Module example
const welcome = {
sayHello : function() {
console.log("Hello Welcome to everyone");
},
currTime : new Date().toLocaleDateString(),
companyName : "Vellore Institute of Technology"
}
module.exports = welcome

Save the file as welcome.js

var local = require("./welcome.js");


local.sayHello();
console.log(local.currTime);
console.log(local.companyName);

Save the file as welcomedemo.js


28 Export Module in Node.js
 Node JS has provided almost all required modules (We can check this updates on its
official website: https://www.npmjs.com/. It is also known as Node JS Module
Repository).
 But in some real time applications, we may have some application functionality,
which is used many places in that application but not available at Node JS Module
Repository.
 In this scenario, to get Reusability benefit, we need to create our own new Node JS
module.
 Just creating new Module is not enough to use it in other modules of the system. We
need to export this module so that other modules will reuse it
29 Export Module in Node.js - example
var PI = 3.1416
exports.PI = PI;

function add(a,b){ return a + b; }


function sub(a,b){ return a - b; }
exports.add = add
exports.sub = sub

exports.arthmetic =
{ var PI = 3.1416;
function add(a,b){ return a + b; }
function sub(a,b){ return a - b; }
function mul(a,b){ return a * b; }
function div(a,b){ return a / b; } }
30 Node.js first example
 Node.js console based example
 console.log("Happy to learn node.js");

 Node.js web-based Example


 A node.js web application contains the following three parts:
 Import required modules: The "require" directive is used to load a Node.js
module.
 Create server: You have to establish a server which will listen to client's request
similar to Apache HTTP Server.
 Read request and return response: Server created in the second step will read
HTTP request made by client which can be a browser or console and return the
response.
31 Node.js web-based Example
 Import required module:
 The first step is to use require directive to load http module and store
returned HTTP instance into http variable
 var http = require("http");
 Create server: In the second step, you have to use created http instance
and call http.createServer() method to create server instance and then
bind it at port 8080 using listen method associated with server instance.
 Pass it a function with request and response parameters and write the
sample implementation to return ―Happy to learn node.js".
 http.createServer(function (request, response) {
 response.writeHead(200, {'Content-Type': 'text/plain'});
 response.end(‘Happy to learn node js\n');
 }).listen(8080);
32 Node.js web-based Example
33 Export module demo
 exports.myDateTime = function () {
return Date();
};
 Save the above file as dateandtime.js
var http = require('http');
var dt = require('./dateandtime');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
Save this file as webbasedex2.js
34 Export module demo output
35 Node.JS url module
 The URL module splits up a web address into readable parts.
 var url = require('url');
 Parse an address with the url.parse() method, and it will return a URL object
with each part of the address as properties:
36 Node.js url demo
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'


console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }


console.log(qdata.month); //returns 'february'
37 Node.js file system module
 Node.js includes fs module to access physical file system. The fs module is
responsible for all the asynchronous or synchronous file I/O operations.
 To include the File System module, use the require() method:
 var fs = require('fs');
 Common use for the File System module:
Read files
Create files
Update files
Delete files
Rename files
38 readFile method
 The fs.readFile() method is used to read files on your system.
 <html>
<body>
<h1>How to use fs module in Node JS</h1>
<p>use require method</p>
</body>
</html>
 Save this file as readdemo.html
 var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile(‘readdemo.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
39 writeFile method
var fs = require('fs');
fs.writeFile('sample.txt', 'File manipulation is very simple in node js', function
(err) {
if (err) throw err;
console.log('Sample.text is created successfully');
});
40 writeFile method (Running web server)
var http = require('http');
var fs = require('fs');
data = "Many of the website creation used by node js";
http.createServer(function (req, res)
{ fs.writeFile('sample.txt', data,function(err, fdata)
{ res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("File is created successfully");
return res.end(); }); }).listen(8080);
41 appendFile method
var fs = require('fs');
fs.appendFile('sample.txt', 'Read, write and append file operation', function
(err) {
if (err) throw err;
console.log('New line of content stored in sample.txt');
});
42 appendFile method (Web Server)
var http = require('http');
var fs = require('fs');
data = "Node.js processes user requests differently when compared to a
traditional web server model";
http.createServer(function (req, res)
{ fs.appendFile('sample.txt', data,function(err, fdata)
{ res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("New content is added to the file.");
return res.end(); }); }).listen(8080);
43 Delete and rename a file
 To delete a file with the File System module, use the fs.unlink() method.
 The fs.unlink() method deletes the specified file.
var fs = require('fs');
//Delete the file sample.txt:
fs.unlink('sample.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
 To rename a file with the File System module, use the fs.rename() method.
 The fs.rename() method renames the specified file:
var fs = require('fs');
fs.rename('sample.txt', 'sampledemo.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});
44 Callback
 A callback is a function called when the task finishes, and a callback
function allows other code to run in the meantime.
 Using the Callback concept, Node. js can process many requests without
waiting for any function to return the result, making Node. js highly scalable.

var fs=require("fs");
var data=fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Task is completed");

var fs=require("fs");
fs.readFile('input.txt', function(err,data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Task is completed");
45 Event loop
 In Node.js, the Call Stack is a fundamental mechanism provided by the V8
JavaScript engine that manages the execution of your program's functions.
 It operates on a Last-In, First-Out (LIFO) principle, meaning the last function
added to the stack is the first one to be removed.
 Tracking Function Execution
 Maintaining Execution Order
 Function Completion and Removal
 Synchronous Execution
 Global Context:
 The entire script you are running is initially considered a "global function"
and is pushed onto the Call Stack when your program starts.
46 Event driven application
 An event-driven application in Node.js program flow is determined
by the occurrence of events.
 This architecture allows Node.js to handle asynchronous operations
efficiently and build scalable, real-time applications.
 Core Concepts:
 Events: These are signals that indicate a particular action or state
change within the application or from external sources.
 Examples include user actions (like a button click),
 system events (like a file being read), or
 messages from other services.
47 Event driven application
 Event Emitters:
 Node.js provides the EventEmitter class (part of the events module)
which objects can inherit from. These objects can "emit" named
events, triggering any registered listeners.
 Event Listeners (or Callbacks):
 These are functions that "listen" for specific events. When an event is
emitted, the corresponding listener function is executed.
 Event Loop:
 This is the central mechanism in Node.js that continuously monitors
for events and executes their respective callback functions.
 It's a single-threaded process that manages the execution of
asynchronous operations without blocking the main thread.
48 Event driven application
 When an event occurs (e.g., a network request
completes, a file is read), it is placed in a queue.
 The Event Loop picks up events from this queue and
dispatches them to their registered listeners.
 The listener functions are executed, performing the
necessary actions in response to the event.
 Because Node.js uses a non-blocking I/O model, the
Event Loop can continue processing other events while
waiting for long-running operations (like I/O) to
complete, making the application highly responsive and
efficient.
49 Event loop- Call Stack
 The Event Loop has one simple job — to monitor the Call Stack and the
Callback Queue.
 If the Call Stack is empty, the Event Loop will take the first event from the
queue and will push it to the Call Stack, which effectively runs it.
 In an event driven application, there is generally a main loop that listens for
events and then triggers a callback function when one of those events is
detected.
50 Event handler in Node js
 In Node.js, event handlers are defined using the built-in events module and
its EventEmitter class.
 This allows for an event-driven architecture where you can create, emit,
and listen for custom events.
 To define an event handler in Node.js:
1. import the events module.
 const EventEmitter = require('events');
2. Create an instance of EventEmitter.
 const myEmitter = new EventEmitter();
3. Define the event handler function: This is the function that will be executed
when the event is triggered.
51 Event handler in Node js
const myEventHandler = function (data) {
console.log('An event occurred with data:', data);
};

You can also define it as an arrow function:

const myEventHandler = (data) => {


console.log('An event occurred with data:', data);
};

4. Register the event handler with an event: Use the on() method to associate
the handler with a specific event name.

myEmitter.on('myCustomEvent', myEventHandler);
52 Event handler in Node js
If you want the handler to be called only once, use once() instead of on():
myEmitter.once('myCustomEvent', myEventHandler);

5. Emit the event: Use the emit() method to trigger the event. You can also pass
arguments to the event handler.

myEmitter.emit('myCustomEvent', 'some important data');


53 Example1 for Event handling in Node.js
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
const welcomeHandler = function (username) {
console.log(`Welcome, ${username}!`); };
// Register the event handler for the 'userJoined' event
myEmitter.on('userJoined', welcomeHandler);
// Emit the 'userJoined' event
myEmitter.emit('userJoined', 'Alice'); // Output: Welcome, Alice!
myEmitter.emit('userJoined', 'Bob'); // Output: Welcome, Bob!
54 Example2 for Event handling in Node.js
const EventEmitter = require('events');
// Create a new instance of EventEmitter
const myEmitter = new EventEmitter();
// Define a listener function
const myListener = function(message) {
console.log(`Received message: ${message}`);
};
// Register the listener for the 'greet' event
myEmitter.on('greet', myListener);
// Emit the 'greet' event
myEmitter.emit('greet', 'Hello from the Event Emitter!');
55 Example2 for Event handling in Node.js
// You can also add multiple listeners to the same event
myEmitter.on('greet', () => {
console.log('Another greeting!');});
// Emit the 'greet' event again to trigger both listeners
myEmitter.emit('greet', 'Second greeting!');
// Remove a specific listener
myEmitter.off('greet', myListener);
// Emit the 'greet' event again; only the second listener will be called
myEmitter.emit('greet', 'Third greeting!');
// Register a listener that only fires once
myEmitter.once('onceEvent', () => {
console.log('This event will only fire once.');});
// Emit the 'onceEvent'
myEmitter.emit('onceEvent'); // Output: This event will only fire once.
myEmitter.emit('onceEvent'); // No output, as the listener was removed after the first emit
56 Event handler in Node js
 The EventEmitter class is imported from the built-in events module.
 An instance of EventEmitter is created as myEmitter.
 A function myListener is defined to serve as an event handler.
 The myEmitter.on() method registers myListener to be executed whenever
the 'greet' event is emitted.
 The myEmitter.emit() method triggers the 'greet' event,
causing myListener to be invoked with the provided message.
 Multiple listeners can be registered for the same event, and emit() will call
all of them.
 The myEmitter.off() method is used to remove a specific listener from an
event.
 The myEmitter.once() method registers a listener that will be called only
once and then automatically removed.
57 Example3 for Event handling in Node.js
const EventEmitter = require('events');
// Create a new instance of EventEmitter
const myEmitter = new EventEmitter();
// Register an event listener for the 'greet' event
myEmitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
// Register another event listener for the 'farewell' event
myEmitter.on('farewell', () => {
console.log('Goodbye!');
});
58 Example3 for Event handling in Node.js
// Emit the 'greet' event with an argument
myEmitter.emit('greet', 'Alice');
// Emit the 'farewell' event
myEmitter.emit('farewell');
// Register a listener that will only be called once
myEmitter.once('firstTime', () => {
console.log('This message will only appear once.');
});
// Emit the 'firstTime' event multiple times
myEmitter.emit('firstTime');
myEmitter.emit('firstTime'); // This emit will not trigger the listener again
59 Removing event listener
 In Node.js, specifically when working with EventEmitter instances,
you can remove event listeners using the removeListener() or
 removeAllListeners() methods.
60 Example 1 for remove listener method
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
function myListener() {
console.log('Event fired!');}
// Add the listener
myEmitter.on('myEvent', myListener);
// Emit the event (will trigger myListener)
myEmitter.emit('myEvent');
// Remove the listener
myEmitter.removeListener('myEvent', myListener);
// Emit the event again (will not trigger myListener)
myEmitter.emit('myEvent');
61 Example 2 for remove listener method
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
function listener1() { console.log('Listener 1'); }
function listener2() { console.log('Listener 2'); }
myEmitter.on('data', listener1);
myEmitter.on('data', listener2);
myEmitter.emit('data'); // Both listeners will fire
myEmitter.removeAllListeners('data'); // Removes all listeners for 'data' event
myEmitter.emit('data'); // No listeners will fire
62 Node.js Event emitter demo 3
const EventEmitter = require('events');
var eventEmitter = new EventEmitter();
var g1= (msg) => {
console.log("How to use eventemitter object: " + msg);
};
var g2 = (msg) => {
console.log("how to register the event: " + msg);
};
eventEmitter.on('myEvent', g1);
eventEmitter.on('myEvent', g1);
eventEmitter.on('myEvent', g2);
eventEmitter.emit('myEvent', "Event occurred");
console.log("Removing listener g1");
eventEmitter.removeListener('myEvent', g1);
eventEmitter.emit('myEvent', "Event occurred");
console.log("Removing all the listeners to myevent");
eventEmitter.removeAllListeners('myEvent');
eventEmitter.emit('myEvent', "Event occurred");
63 Event handling exercises
1. Create and Emit a Simple Event:
a. Create an instance of EventEmitter.
b. Register a listener for a custom event, e.g., ‘greetings', that logs a message
to the console.
c. Emit the 'greetings' event.
2. Modify the previous exercise to pass a name argument when emitting the
'greetings' event. Update the listener to receive and display the name.
3. Register two different listeners for the same event, e.g., 'dataReceived'.
Remove one of the listeners using myEmitter.removeListener(). Emit the event
and observe which listener is still active.
4. Create an EventEmitter to simulate a data source.Emit a 'data' event at
regular intervals (e.g., using setInterval) with simulated data. Register a listener
to process the received data.
64 NPM - Node Package Manager
 Node Package Manager (NPM) is a command line tool that installs,
updates or uninstalls Node.js packages in your application
 NPM is included with Node.js installation
 NPM performs the operation in two modes: global and local. In the global
mode, NPM performs operations which affect all the Node.js applications
on the computer whereas in the local mode, NPM performs operations for
the particular local directory which affects an application in that directory
only.
 Use the following command to install any third party module in your local
Node.js project folder.
 npm install <module name>
65 NPM - Node Package Manager
 npm install express
 All the modules installed using NPM are installed
under node_modules folder. The above command will create ExpressJS
folder under node_modules folder in the root folder of your project and
install Express.js there.
 Use --save at the end of the install command to add dependency entry into
package.json of your application.
 npm install express –-save
 Install Package Globally
 npm install -g express
 Update Package
 npm update <module name> npm update express
66 NPM - Node Package Manager
 Uninstall Packages
 npm uninstall <package name>
 npm uninstall express
 npm –ls
 npm search express
67 Express framework
 Express.js is a web application framework for Node.js. It provides various
features that make web application development fast and easy which
otherwise takes more time using only Node.js.
 Express.js is based on the Node.js middleware module
called connect which in turn uses http module. So, any middleware which is
based on connect will also work with Express.js.
68 Features of express framework
 Makes Node.js web application development fast and easy.
 Easy to configure and customize.
 Allows you to define routes of your application based on HTTP methods and
URLs.
 Includes various middleware modules which you can use to perform
additional tasks on request and response.
 Easy to integrate with different template engines like Jade, Vash, EJS etc.
 Allows you to define an error handling middleware.
 Easy to serve static files and resources of your application.
 Allows you to create REST API server.
 Easy to connect with databases such as MongoDB, Redis, MyS
69 Installing express
 npm install express --save
 body-parser: This is a node.js middleware for handling JSON, Raw, Text and
URL encoded form data.
 cookie-parser: It is used to parse Cookie header and populate req.cookies
with an object keyed by the cookie names.
 multer: This is a node.js middleware for handling multipart/form-data.
 npm install body-parser --save
 npm install cookie-parser --save
 npm install multer --save
70 Express.js App Example
 simple Express app example which starts a server and listen on a local port.
It only responds to homepage
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
71 Express.js App Example
 Requiring Express: const express = require('express'); imports the
Express library.
 Creating an Express application instance: const app = express();
creates the main application object.
 Defining routes: app.get('/', ...) defines how the server responds to
GET requests to specific URLs.
 Starting the server: app.listen(port, ...) makes the application listen
for incoming requests on a specified port.
72 Express.js Request Object
 Express.js Request and Response objects are the parameters of the
callback function which is used in Express applications.
 The express.js request object represents the HTTP request and has properties
for the request query string, parameters, body, HTTP headers, and so on.

app.get('/', function (req, res) {


// --
})
73 Express.JS request object properties
Properties Description

req.app This is used to hold a reference to the instance of the express application that is
using the middleware.

req.body It contains key-value pairs of data submitted in the request body. By default, it is
undefined, and is populated when you use body-parsing middleware such as
body-parser.

req.cookies When we use cookie-parser middleware, this property is an object that contains
cookies sent by the request.

req.params An object containing properties mapped to the named route ?parameters?. For
example, if you have the route /user/:name, then the "name" property is available
as req.params.name. This object defaults to {}

req.query An object containing a property for each query string parameter in the route.

req.route The currently-matched route, a string.

req.signedcookies When using cookie-parser middleware, this property contains signed cookies
sent by the request, unsigned and ready for use.
74 Example for req.app
const express = require('express');
const app = express();
const PORT = 3000;
// Set an application-level variable
app.set('appName', 'Rama');
app.get('/', (req, res) => {
// Access the application name using req.app.get()
const appName = req.app.get('appName');
res.send(`Welcome to ${appName}!`);
});
app.listen(PORT, () => {
console.log(`Server listening on PORT ${PORT}`);
});
75 Example for req.params
const express = require('express');
const app = express();
// Route with a route parameter ':name'
app.get('/users/:name', (req, res) => {
const userName = req.params.name; // userName will be the value from the
URL path
res.send(`Hello, ${userName}!`);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
76 Example for req.query
In Express.js, req.query is an object that contains the query string parameters from
the URL. These parameters are typically used for filtering, sorting, or providing
optional data to a route.

const express = require('express');


const app = express();
const PORT = 3000;
// Define a route that uses query parameters
app.get('/search', (req, res) => {
// Access query parameters using req.query
const searchTerm = req.query.q; // e.g., 'javascript'
const pageNumber = req.query.page; // e.g., '2'
const category = req.query.category; // e.g., 'programming'
// You can perform actions based on these parameters
if (searchTerm) {
console.log(`Searching for: ${searchTerm}`);
}
77 Example for req.query
if (pageNumber) {
console.log(`Requested page: ${pageNumber}`);
}
if (category) {
console.log(`Filtering by category: ${category}`);
}
// Send a response back to the client
res.send(`Search results for "${searchTerm}" on page ${pageNumber} in
category "${category}"`);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
78 Express.JS request methods
 req.accepts (types)
 This method is used to check whether the specified content types are
acceptable, based on the request's Accept HTTP header field.
req.accepts('html');
//=>?html?
req.accepts('text/html');
// => ?text/html?
 req.get(field)
 This method returns the specified HTTP request header field.
req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
79 Express.JS request methods
 req.is(type)
 This method returns true if the incoming request's "Content-Type" HTTP
header field matches the MIME type specified by the type parameter
req.is('html');
req.is('text/html');
req.is('text/*');
// => true
 req.param(name [, defaultValue])
 This method is used to fetch the value of param name when present.
// ?name=sasha
req.param('name')
80 Express.js Response Object
 The Response object (res) specifies the HTTP response which is sent by an
Express app when it gets an HTTP request.
 It sends response back to the client browser.
 It facilitates you to put new cookies value and that will write to the client
browser (under cross domain rule).
 Response properties
Properties Description

res.app It holds a reference to the instance of the express application that


is using the middleware.
res.headersS It is a Boolean property that indicates if the app sent HTTP
ent headers for the response.
res.locals It specifies an object that contains response local variables
scoped to the request
81 Express.js response object method
 Response Attachment method
res.attachment('path/to/js_pic.png');
 Response Cookie method res.cookie(name, value [, options])
res.cookie('name', 'Aryan', { domain: '.xyz.com', path: '/admin', secure:
true });
res.cookie('Section', { Names: [Aryan,Sushil,Priyanka] });
res.cookie('Cart', { items: [1,2,3] }, { maxAge: 900000 });
 Response ClearCookie method res.clearCookie(name [, options])
res.cookie('name', 'Aryan', { path: '/admin' });
 Response End method res.end([data] [, encoding])
 Response Get method res.get(field) res.get('Content-Type');
 Response JSON method:
res.json([body]) res.json({ name: 'ajeet' })
 Response Send method rre res

 .....some html

 ');
82 Express.js response object method
res.send({ some: 'json' });
res.send('
.....some html
');
 Response Set method res.set(field [, value]) res.set('Content-
Type', 'text/plain');
 Response Type method
res.type('.html'); // => 'text/html'
res.type('html'); // => 'text/html'
res.type('json'); // => 'application/json'
res.type('application/json'); // => 'application/json'
res.type('png'); // => image/png:
 Response sendFile method res.sendFile(fileName, options, function (err) {
 // ...
 });
83 Middleware function
 Middleware functions are functions that have access to the request
object (req), the response object (res), and the next function in the
application’s request-response cycle.
 The next function is a function in the Express router which, when invoked,
executes the middleware succeeding the current middleware.
 Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware in the stack.
 If the current middleware function does not end the request-response
cycle, it must call next() to pass control to the next middleware function
84 Middleware function call
85 Express.js GET Request
 GET and POST both are two common HTTP requests used for building
REST API's.
 GET requests are used to send only limited amount of data because
data is sent into header while POST requests are used to send large
amount of data because data is sent in the body.
86 Form get method demo
<html>
<body>
<form action="http://localhost:8000/formex1" method="GET">
First Name: <input type="text" name="first_name"/> <br/>
Last Name: <input type="text" name="last_name"/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Save it as form1.html
87 Form get method processing – formex1.js
var express = require('express');
var app=express();
app.get('/formex1', function (req, res) {
res.send('<h1>Username: ' + req.query['first_name']+'</h1><h1>Lastname:
'+req.query['last_name']+'</h1>');
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
88 Form get method – example 2
<!DOCTYPE html>
<html>
<body>
<form action="http://localhost:8000/formex2">
<table>
<tr><td>Enter First Name:</td><td><input type="text" name="firstname"/><td></tr>
<tr><td>Enter Last Name:</td><td><input type="text" name="lastname"/><td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="password"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"> Male
<input type="radio" name="sex" value="female">Female
</td></tr>
<tr><td>About You :</td><td>
<textarea rows="5" cols="40" name="aboutyou" placeholder="Write about yourself">
</textarea>
</td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>
</body>
</html>
89 Form get method processing – formex2.js
var express = require('express');
var app=express();
app.get('/formex2', function (req, res) {
res.send('<p>Firstname: ' + req.query['firstname']+'</p> <p>Lastname:
'+req.query['lastname']+'</p><p>Password: '+req.query['password']+'</p>
<p>AboutYou: '+req.query['aboutyou']+'</p>');
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

You might also like