UNIT-2 AWD NodeJS
UNIT-2 AWD NodeJS
Express is a minimal and flexible Node.js web application framework that provides a robust set of
features for web and mobile applications. It is an open source framework developed and maintained
by the Node.js foundation.
What is Express.js?
Express provides a minimal interface to build our applications. It provides us the tools that are required
to build our app. It is flexible as there are numerous modules available on npm, which can be directly
plugged into Express.
Features of ExpressJS
Following are the salient features of ExpressJS making it a default choice among web application
developers.
• Middleware/Routing− ExpressJS provides clear options for Routes with support for all kind of
HTTP methods like POST, GET, PUT etc.
• Templating− ExpressJS supports various templating engines like PUG, Jade or EJS to generate
HTML content on the fly.
• Static File Serve− ExpressJS supports static files like images/css/javascript from a folder
seemlessly.
Applications of ExpressJS
Following are the salient features of ExpressJS making it a default choice among web application
developers.
• Support RESTful APIs− REST Architecture is very powerful style to enable communication of
front-end with backend. ExpressJS supports RESTful APIs by design.
• Support for Real Time Applications− Event Driven Programming helps to create chat, parallel
collaborative editing tools etc. ExpressJS integrates with Node and supports Event Driven
Programming seemlessly.
1
UNIT-2 : Advance Web Development (ExpressJS)
• Support for Single Page Applications(SPA)− SPA and RESTFul APIs allows Express Based
application to update content dynamically enriching user experience.
Once node is installed, you can run the following npm command inside the Node project where
package.json is residing.
To make our development process a lot easier, we will install a tool from npm, nodemon. This tool
restarts our server as soon as we make a change in any of our files, otherwise we need to restart the
server manually after each file modification. To install nodemon, use the following command −
Once express set up is complete, we can start developing our first app using Express. Create a new file
called index.js and type the following in it.
res.send("Hello world!");
});
app.listen(3000);
nodemon index.js
This will start the server. To test this app, open your browser and go to http://localhost:3000 and a
message will be displayed as in the following screenshot.
2
UNIT-2 : Advance Web Development (ExpressJS)
There are two ways to install a package using npm: globally and locally.
• Globally − This method is generally used to install development tools and CLI based packages.
To install a package globally, use the following code.
• Locally − This method is generally used to install frameworks and libraries. A locally installed
package can be used only within the directory it is installed. To install a package locally, use
the same command as above without the -g flag.
Whenever we create a project using npm, we need to provide a package.json file, which has all the
details about our project. npm makes it easy for us to set up this file. Let us set up our development
project.
Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create directory)
into it −
E:\Dev>mkdir hello-world
3
UNIT-2 : Advance Web Development (ExpressJS)
E:\Dev>cd hello-world
E:\Dev\hello-world>
Step 2 − Now to create the package.json file using npm, use the following code.
E:\Dev\hello-world>npm init -y
E:\Dev\hello-world>npm init
Just keep pressing enter, and enter your name at the author name field.
Step 3 − Now we have our package.json file set up, we will further install Express.
To install Express and add it to our package.json file, use the following command −
found 0 vulnerabilities
Tip − The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a
dependency to our package.json file. This has an advantage, the next time we need to install all the
dependencies of our project we can just run the command npm install and it will find the
dependencies in this file and install them for us.
This is all we need to start development using the Express framework. To make our development
process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as
we make a change in any of our files, otherwise we need to restart the server manually after each file
modification. To install nodemon, use the following command −
added 29 packages in 2s
Routing in ExpressJS
Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes.
Syntax:
app.method(path, handler)
4
UNIT-2 : Advance Web Development (ExpressJS)
This METHOD can be applied to any one of the HTTP verbs get, set, put, delete. An alternate method
also exists, which executes independent of the request type.
Handler is a callback function that executes when a matching request type is found on the relevant
route. For example,
index.js
res.send("Hello World!");
});
app.listen(3000);
If we run our application and go to localhost:3000/hello, the server receives a get request at
route "/hello", our Express app executes the callback function attached to this route and sends "Hello
World!" as the response.
We can also have multiple different methods at the same route. For example,
index.js
5
UNIT-2 : Advance Web Development (ExpressJS)
res.send("Hello World!");
});
});
app.listen(3000);
To test this request, open postman. Now hit the below URL's in POSTMAN application and you can see
the output−
A special method, all, is provided by Express to handle all types of http methods at a particular route
using the same function. To use this method, try the following.
6
UNIT-2 : Advance Web Development (ExpressJS)
});
Routers
Defining routes like above is very tedious to maintain. To separate the routes from our
main index.js file, we will use Express.Router. Create a new file called things.js and type the following
in it.
things.js
});
});
module.exports = router;
Now to use this router in our index.js, type in the following before the app.listen function call.
res.send("Hello World!");
});
7
UNIT-2 : Advance Web Development (ExpressJS)
app.use('/things', things);
app.listen(3000);
The app.use function call on route '/things' attaches the things router with this route. Now whatever
requests our app gets at the '/things', will be handled by our things.js router. The '/' route in things.js
is actually a subroute of '/things'. Visit localhost:3000/things/ and you will see the following output.
Routers are very helpful in separating concerns and keep relevant portions of our code together. They
help in building maintainable code. You should define your routes relating to an entity in a single file
and include it using the above method in your index.js file.
The HTTP method is supplied in the request and specifies the operation that the client has requested.
The following table lists the most used HTTP methods −
GET
1 The GET method requests a representation of the specified resource. Requests using GET should
only retrieve data and should have no other effect.
POST
2 The POST method requests that the server accept the data enclosed in the request as a new
object/entity of the resource identified by the URI.
3 PUT
8
UNIT-2 : Advance Web Development (ExpressJS)
The PUT method requests that the server accept the data enclosed in the request as a
modification to existing object identified by the URI. If it does not exist then the PUT method
should create one.
DELETE
4
The DELETE method requests that the server delete the specified resource.
These are the most common HTTP methods. To learn more about the methods,
visit http://www.tutorialspoint.com/http/http_methods.htm.
Example
Create a new file called index.js in hello-world directory and type the following in it.
index.js
res.send("GET Request!");
});
res.send("POST Request!");
});
res.send("PUT Request!");
});
res.send("DELETE Request!");
});
app.listen(3000);
9
UNIT-2 : Advance Web Development (ExpressJS)
E:\Dev\hello-world>nodemon index.js
[nodemon] 3.1.9
This will start the server. To test this app, open your browser and go to http://localhost:3000 and a
message will be displayed as in the following screenshot.
To test other requests, open postman. Now hit the below URL's in POSTMAN application and you can
see the output−
10
UNIT-2 : Advance Web Development (ExpressJS)
11
UNIT-2 : Advance Web Development (ExpressJS)
Types of Middleware
1. Application-level middleware: Binds to an instance of the app object.
Implementing Middlewares
Implementing middleware in Express.js involves using app.use() for application-level middleware
and router.use() for router-level middleware. Middleware functions can be chained and executed
sequentially, allowing for complex request processing and response handling. Error-handling
middleware is defined with four arguments and used after other middleware and route definitions.
12
UNIT-2 : Advance Web Development (ExpressJS)
Express also provides built-in middleware for common tasks, and you can also utilize third-party
middleware to extend functionality.
Application-Level Middleware
Example:
// Application-level middleware
console.log('Application-level middleware.');
});
res.send('Hello, World!');
});
app.listen(3000, () => {
});
Router-Level Middleware
Example:
13
UNIT-2 : Advance Web Development (ExpressJS)
});
// Route handler
res.send('Router Middleware');
});
app.listen(3000, () => {
});
Error-Handling Middleware
Error-handling middleware functions have four arguments: (err, req, res, next). They are defined after
other app.use() and route calls.
Example:
});
// Error-handling middleware
14
UNIT-2 : Advance Web Development (ExpressJS)
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => {
});
Built-in Middleware
Example:
app.use(express.json());
});
app.listen(3000, () => {
});
Third-Party Middleware
Many third-party middleware is available to add specific functionality to your Express application.
Morgan is a popular logging middleware.
Example:
15
UNIT-2 : Advance Web Development (ExpressJS)
app.use(morgan('combined'));
});
app.listen(3000, () => {
});
Express.js utilizes request and response objects to handle incoming HTTP requests and outgoing HTTP
responses. These objects are essential for managing interactions in developing robust and efficient
web applications. This tutorial aims to provide a comprehensive understanding of these objects'
functionalities and demonstrate how to implement them effectively in Express.js applications.
The request object, often abbreviated as req, represents the HTTP request and includes various
properties that provide details about the incoming request.
• req.body: Contains data sent in the request body (requires body-parser middleware).
Query parameters are the key-value pairs in the URL after the ? mark. You can access them using
the req.query object. Here's an example:
Example:
16
UNIT-2 : Advance Web Development (ExpressJS)
if (queryParam) {
} else {
});
app.listen(3000, () => {
});
Route parameters are named segments of the URL, specified by colon prefixes, that capture values at
specific positions within the URL. Here's how you can access route parameters in an Express.js
application:
Example:
17
UNIT-2 : Advance Web Development (ExpressJS)
});
app.listen(3000, () => {
});
To access the request body in an Express.js application, you typically need to use middleware that can
parse the body of incoming requests. Here's an example using the built-in express.json() middleware
to parse JSON-formatted request bodies:
Example:
app.use(express.json());
// Define a route to access and respond with data from the request body
18
UNIT-2 : Advance Web Development (ExpressJS)
});
app.listen(3000, () => {
});
Here's an example demonstrating how to access the HTTP method used in a request:
Example:
});
app.listen(3000, () => {
});
19
UNIT-2 : Advance Web Development (ExpressJS)
Here's an example demonstrating how to access and respond with the URL of an incoming request in
an Express.js application:
Example:
});
app.listen(3000, () => {
});
Here's an example of how to access request headers in an Express.js application. This code
demonstrates setting up a route that reads and responds with the headers sent by the client:
Example:
20
UNIT-2 : Advance Web Development (ExpressJS)
res.json(headers);
});
app.listen(3000, () => {
});
The response object, commonly abbreviated as res, represents the HTTP response that an Express app
sends when it gets an HTTP request. It includes methods for setting the response status, headers, and
body.
Sending Response
Here's an example showing how to send various types of responses using Express.js. This example
covers sending plain text, HTML content, and JSON, demonstrating the versatility of
the res.send() method:
Example:
21
UNIT-2 : Advance Web Development (ExpressJS)
});
});
});
app.listen(3000, () => {
});
22
UNIT-2 : Advance Web Development (ExpressJS)
Here's an example of how to send a JSON response using Express.js. This code demonstrates setting
up a route that responds with JSON data when accessed:
Example:
const data = {
name: 'Alex',
age: 30,
occupation: 'Engineer'
};
res.json(data);
});
app.listen(3000, () => {
});
Here's an example demonstrating how to set the HTTP response status in an Express.js application:
Example:
23
UNIT-2 : Advance Web Development (ExpressJS)
});
app.listen(3000, () => {
});
Example:
res.redirect('https://www.example.com');
});
app.listen(3000, () => {
24
UNIT-2 : Advance Web Development (ExpressJS)
});
Here's an example of how you can use the res.render() method in Express.js to render views using a
template engine:
Example:
// Set the view engine to ejs and specify the views directory
});
app.listen(3000, () => {
});
Here's an example demonstrating how to send a file response using Express.js. This example serves a
specific file from a given path when a particular route is accessed:
Example:
25
UNIT-2 : Advance Web Development (ExpressJS)
res.sendFile(filePath, function(err) {
if (err) {
} else {
});
});
app.listen(3000, () => {
});
Error handling in Express is done using middleware. But this middleware has special properties. The
error handling middleware are defined in the same way as other middleware functions, except that
error-handling functions MUST have four arguments instead of three err, req, res, next. For example,
to send a response on any error, we can use −
26
UNIT-2 : Advance Web Development (ExpressJS)
console.error(err.stack);
res.status(500).send('Something broke!');
});
Till now we were handling errors in the routes itself. The error handling middleware allows us to
separate our error logic and send responses accordingly. The next() method we discussed in
middleware takes us to next middleware/route handler.
For error handling, we have the next(err) function. A call to this function skips all middleware and
matches us to the next error handler for that route. Let us understand this through an example.
index.js
next(err);
});
/*
* ....
*/
res.status(500);
});
app.listen(3000);
Output
27
UNIT-2 : Advance Web Development (ExpressJS)
This error handling middleware can be strategically placed after routes or contain conditions to detect
error types and respond to the clients accordingly. The above program will display the following
output.
found 0 vulnerabilities
index.js
28
UNIT-2 : Advance Web Development (ExpressJS)
res.render('form');
});
app.set('views', './views');
app.use(bodyParser.json());
//form-urlencoded
app.use(upload.array());
app.use(express.static('public'));
console.log(req.body);
});
app.listen(3000);
After importing the body parser and multer, we will use the body-parser for parsing json and x-www-
form-urlencoded header requests, while we will use multer for parsing multipart/form-data.
Let us create an html form to test this out. Create a new view called form.pug with the following code
−
form.pug
html
head
29
UNIT-2 : Advance Web Development (ExpressJS)
body
div
br
div
br
E:\Dev\hello-world>nodemon index.js
[nodemon] 3.1.9
Now go to localhost:3000/ and fill the form as you like, and submit it.
30
UNIT-2 : Advance Web Development (ExpressJS)
Have a look at your console; it will show you the body of your request as a JavaScript object as in the
following screenshot −
E:\Dev\hello-world>nodemon index.js
[nodemon] 3.1.9
The req.body object contains your parsed request body. To use fields from that object, just use them
like normal JS objects.
This is the most recommended way to send a request. There are many other ways, but those are
irrelevant to cover here, because our Express app will handle all those requests in the same way. To
read more about different ways to make a request, have a look at this page.
javascript
31
UNIT-2 : Advance Web Development (ExpressJS)
app.use(cors());
app.listen(3000, () => {
});
javascript
const corsOptions = {
maxAge: 86400 // How long the results of a preflight request can be cached (in seconds)
};
app.use(cors(corsOptions));
Route-Specific CORS
javascript
app.use(cors());
});
32
UNIT-2 : Advance Web Development (ExpressJS)
javascript
const corsOptions = {
callback(null, true);
} else {
};
app.use(cors(corsOptions));
javascript
app.use(express.json());
bash
33
UNIT-2 : Advance Web Development (ExpressJS)
javascript
app.use(bodyParser.json());
javascript
// Middleware setup
app.use(express.json());
res.send('Hello World!');
});
34
UNIT-2 : Advance Web Development (ExpressJS)
});
app.listen(3000, () => {
});
Common Options
• extended: true - allows rich objects and arrays to be encoded into the URL-encoded format
• type: 'application/json' - determines which media type the middleware will parse
html
<button type="submit">Login</button>
</form>
Or test with a tool like Postman by sending a POST request with a JSON body.
javascript
// For JSON
app.use(express.json());
app.use(express.raw());
35
UNIT-2 : Advance Web Development (ExpressJS)
app.use(express.text());
Now that we’ve met our cast of characters, let’s set the stage for our web development adventure.
Here’s how to set up your MERN stack environment:
Download and install Node.js from the official website. NPM comes bundled with it, so you’re all set!
node -v
npm -v
2. Set Up MongoDB
Install MongoDB locally or use a cloud service like MongoDB Atlas. It’s like choosing between a home-
cooked meal or takeout—both are great, but one requires a bit more effort.
mongodb
mkdir my-mern-app
cd my-mern-app
npm init -y
5. Install Express.js
6. Set Up React
7. Install Mongoose
Create a file named server.js in your project root and set up a basic Express server:
36
UNIT-2 : Advance Web Development (ExpressJS)
app.listen(PORT, () => {
});
37