KEMBAR78
UNIT-2 AWD NodeJS | PDF | Java Script | Software
0% found this document useful (0 votes)
50 views37 pages

UNIT-2 AWD NodeJS

Uploaded by

sen.ankita555
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)
50 views37 pages

UNIT-2 AWD NodeJS

Uploaded by

sen.ankita555
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/ 37

UNIT-2 : Advance Web Development (ExpressJS)

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.

Why Learn Express.js?


Express Framework unlike its competitors like Rails and Django, which have an opinionated way of
building applications, has no "best way" to do something. It is very flexible and pluggable. It uses Pug,
a template language for writing HTML templates.

Features of ExpressJS
Following are the salient features of ExpressJS making it a default choice among web application
developers.

• Minimalistic Design− ExpressJS is an unopinionated. ExpressJS framework is highly flexible


with a simple, minimalistic design principles. We can quickly setup server, define routes and
start handling http requests with very few lines of code.

• Middleware/Routing− ExpressJS provides clear options for Routes with support for all kind of
HTTP methods like POST, GET, PUT etc.

• Flexibility− There is no prerequisites or any format to follow in order to use ExpressJS. If we


know NodeJS, we can write code as per our preference.

• 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.

• NodeJS Based− Core functionalities of asynchronous programming and event driven


programming features of NodeJS can be integrated with ExpressJS easily.

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.

How to Install Express.js?


Express requires Node.JS and NPM to be installed first. Different operating systems required different
steps to install Node.js, please follow the provided methods according to your installed operating
system.

• Node.js Installation on Windows

• Node.js Installation on Linux - Ubuntu

Once node is installed, you can run the following npm command inside the Node project where
package.json is residing.

npm install --save express

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 −

npm install -g nodemon

Example of Express.js Application

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.

var express = require('express');

var app = express();

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

res.send("Hello world!");

});

app.listen(3000);

Save the file, go to your terminal and type the following.

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)

Node Package Manager(npm)


npm is the package manager for node. The npm Registry is a public collection of packages of open-
source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs
of the JavaScript community. npm allows us to access all these packages and install them locally. You
can browse through the list of packages available on npm at npmJS.

How to use npm?

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.

npm install -g <package-name>

• 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.

npm install <package-name>

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

It will ask you for the following information.

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 −

E:\Dev\hello-world>npm install --save express

added 69 packages, and audited 70 packages in 4s

14 packages are looking for funding

run `npm fund` for details

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 −

E:\Dev\hello-world>npm install -g nodemon

added 29 packages in 2s

4 packages are looking for funding

run `npm fund` for details

Routing in ExpressJS
Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes.

The following function is used to define routes in an Express application –

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.

Path is the route at which the request will run.

Handler is a callback function that executes when a matching request type is found on the relevant
route. For example,

index.js

var express = require('express');

var app = express();

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

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

var express = require('express');

5
UNIT-2 : Advance Web Development (ExpressJS)

var app = express();

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

res.send("Hello World!");

});

app.post('/hello', function(req, res){

res.send("You just called the post method at '/hello'!\n");

});

app.listen(3000);

To test this request, open postman. Now hit the below URL's in POSTMAN application and you can see
the output−

POST Request http://localhost:3000/hello

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)

app.all('/test', function(req, res){

res.send("HTTP method doesn't have any effect on this route!");

});

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

var express = require('express');

var router = express.Router();

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

res.send('GET route on things.');

});

router.post('/', function(req, res){

res.send('POST route on things.');

});

//export this router to use in our index.js

module.exports = router;

Now to use this router in our index.js, type in the following before the app.listen function call.

var express = require('Express');

var app = express();

var things = require('./things.js');

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

res.send("Hello World!");

});

//both index.js and things.js should be in same directory

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 −

S.No. Method & Description

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

var express = require('express');

var app = express();

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

res.send("GET Request!");

});

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

res.send("POST Request!");

});

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

res.send("PUT Request!");

});

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

res.send("DELETE Request!");

});

app.listen(3000);

Save the file, go to your terminal and type the following.

9
UNIT-2 : Advance Web Development (ExpressJS)

E:\Dev\hello-world>nodemon index.js

[nodemon] 3.1.9

[nodemon] to restart at any time, enter `rs`

[nodemon] watching path(s): *.*

[nodemon] watching extensions: js,mjs,cjs,json

[nodemon] starting `node 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.

To test other requests, open postman. Now hit the below URL's in POSTMAN application and you can
see the output−

POST Request http://localhost:3000/

10
UNIT-2 : Advance Web Development (ExpressJS)

Similary you can test the other urls.

PUT Request http://localhost:3000/

11
UNIT-2 : Advance Web Development (ExpressJS)

DELETE Request http://localhost:3000/

What is Middleware in ExpressJS?


Middleware in Express.js refers to functions that have access to the request and response objects, as
well as the next middleware function in the application’s request-response cycle. These functions can
perform various operations, including executing code, modifying the request and response objects,
terminating the request-response cycle, handling cookies, logging requests, and passing control to
subsequent middleware functions.

Types of Middleware
1. Application-level middleware: Binds to an instance of the app object.

2. Router-level middleware: Binds to an instance of express.Router().

3. Error-handling middleware: Special middleware that handles errors.

4. Built-in middleware: Provided by Express, such as express.json() and express.static().

5. Third-party middleware: Provided by the community, like Morgan, for logging.

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

Application-level middleware is attached to an instance of the app object


through app.use() and app.METHOD(), where the METHOD is an HTTP method.

Example:

Copy Codeconst express = require('express');

const app = express();

// Application-level middleware

app.use((req, res, next) => {

console.log('Application-level middleware.');

console.log(`Request method: ${req.method}, URL: ${req.url}, Time: ${Date.now()}`);

next(); // Proceed to the next middleware

});

// Route handler for the root URL

app.get('/', (req, res) => {

res.send('Hello, World!');

});

// Start the server

app.listen(3000, () => {

console.log('The server is running on port 3000.');

});

Router-Level Middleware

Router-level middleware works like application-level middleware, except it is bound to an instance


of express.Router(). Router-level middleware can be scoped to specific URL paths within a router.

Example:

Copy Codeconst express = require('express');

const app = express();

const router = express.Router();

13
UNIT-2 : Advance Web Development (ExpressJS)

// Middleware function for router

router.use((req, res, next) => {

console.log('Request URL:', req.originalUrl);

next(); // Proceed to the next middleware

});

// Route handler

router.get('/', (req, res) => {

res.send('Router Middleware');

});

app.use('/router', router); // Apply router middleware

app.listen(3000, () => {

console.log('The server is running on port 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:

Copy Codeconst express = require('express');

const app = express();

// Middleware to trigger an error

app.get('/', (req, res) => {

throw new Error('BROKEN'); // Express will catch this on its own.

});

// Error-handling middleware

app.use((err, req, res, next) => {

14
UNIT-2 : Advance Web Development (ExpressJS)

console.error(err.stack);

res.status(500).send('Something broke!');

});

app.listen(3000, () => {

console.log('The server is running on port 3000.');

});

Built-in Middleware

Express provides built-in middleware to handle common tasks. For


instance, express.json() and express.urlencoded() parse JSON and URL-encoded data.

Example:

Copy Codeconst express = require('express');

const app = express();

// Built-in middleware to parse JSON

app.use(express.json());

app.post('/data', (req, res) => {

res.send(`Received data: ${JSON.stringify(req.body)}`);

});

app.listen(3000, () => {

console.log('The server is running on port 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:

Copy Codeconst express = require('express');

const morgan = require('morgan');

const app = express();

15
UNIT-2 : Advance Web Development (ExpressJS)

// Using third-party middleware for logging

app.use(morgan('combined'));

app.get('/', (req, res) => {

res.send('Logging with Morgan');

});

app.listen(3000, () => {

console.log('The server is running on port 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.

Understanding the Request Object

The request object, often abbreviated as req, represents the HTTP request and includes various
properties that provide details about the incoming request.

Key Properties and Methods of the Request Object

• req.query: Contains the URL query parameters.

• req.params: Contains route parameters.

• req.body: Contains data sent in the request body (requires body-parser middleware).

• req.method: The HTTP method used (GET, POST, etc.).

• req.url: The URL of the request.

• req.headers: Contains the headers of the request.

Accessing Query Parameters

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:

Copy Code// Require the Express module

const express = require('express');

// Create an Express application

16
UNIT-2 : Advance Web Development (ExpressJS)

const app = express();

// Define a route that accesses and returns query parameters

app.get('/search', (req, res) => {

// Access the query parameter 'q' from the request

const queryParam = req.query.q;

// Check if the query parameter exists

if (queryParam) {

// Respond with the query parameter value

res.send(`Search query: ${queryParam}`);

} else {

// Respond with an error message if 'q' is not provided

res.status(400).send('Query parameter "q" is required');

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Accessing Route Parameters

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:

Copy Code// Require the Express module

const express = require('express');

// Create an Express application

const app = express();

17
UNIT-2 : Advance Web Development (ExpressJS)

// Define a route with a parameter for user ID

app.get('/user/:id', (req, res) => {

// Access the route parameter 'id' from the request

const userId = req.params.id;

// Respond with the user ID

res.send(`User ID: ${userId}`);

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Accessing Request Body

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:

Copy Code// Require the Express module

const express = require('express');

// Create an Express application

const app = express();

// Use middleware to parse JSON bodies

app.use(express.json());

// Define a route to access and respond with data from the request body

app.post('/profile', (req, res) => {

// Access the body from the request

const requestBody = req.body;

18
UNIT-2 : Advance Web Development (ExpressJS)

// Respond with the data from the request body

res.send(`Received the following data: ${JSON.stringify(requestBody)}`);

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Accessing HTTP Method

Here's an example demonstrating how to access the HTTP method used in a request:

Example:

Copy Code// Require the Express module

const express = require('express');

// Create an Express application

const app = express();

// Define a route that accesses and returns the HTTP method

app.all('/method', (req, res) => {

// Access the HTTP method from the request

const method = req.method;

// Respond with the HTTP method used

res.send(`HTTP Method used in the request: ${method}`);

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Accessing Request URL

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:

Copy Code// Require the Express module

const express = require('express');

// Create an Express application

const app = express();

// Define a route that accesses and returns the request URL

app.get('/request-url', (req, res) => {

// Access the URL from the request

const requestUrl = req.url;

// Respond with the request URL

res.send(`The requested URL is: ${requestUrl}`);

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Accessing Request Headers

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:

Copy Code// Require the Express module

const express = require('express');

// Create an Express application

const app = express();

20
UNIT-2 : Advance Web Development (ExpressJS)

// Define a route to access and return request headers

app.get('/headers', (req, res) => {

// Access the headers from the request

const headers = req.headers;

// Respond with the headers in JSON format

res.json(headers);

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Understanding the Response Object

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.

Key Properties and Methods of the Response Object

• res.send(): Sends a response of various types.

• res.json(): Sends a JSON response.

• res.status(): Sets the HTTP status for the response.

• res.redirect(): Redirects to a specified URL.

• res.render(): Renders a view template.

• res.sendFile(): Sends a file as an octet stream.

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:

Copy Code// Require the Express module

const express = require('express');

21
UNIT-2 : Advance Web Development (ExpressJS)

// Create an Express application

const app = express();

// Define a route to send a plain text response

app.get('/text', (req, res) => {

// Send plain text response

res.send('Hello, this is a plain text response!');

});

// Define a route to send HTML content

app.get('/html', (req, res) => {

// Send HTML response

res.send('<h1>Hello World</h1><p>This is an HTML response.</p>');

// Optionally, log the response to the console

console.log('Sent an HTML response');

});

// Define a route to send a JSON response

app.get('/json', (req, res) => {

// Send JSON response

res.send({ message: 'This is a JSON response', status: 'Success' });

// Optionally, log the response to the console

console.log('Sent a JSON response');

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Sending a JSON Response

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:

Copy Code// Require the Express module

const express = require('express');

// Create an Express application

const app = express();

// Define a route that sends a JSON response

app.get('/json', (req, res) => {

// Define the JSON data to send

const data = {

name: 'Alex',

age: 30,

occupation: 'Engineer'

};

// Send the JSON response

res.json(data);

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Setting the Response Status

Here's an example demonstrating how to set the HTTP response status in an Express.js application:

Example:

Copy Code// Require the Express module

const express = require('express');

23
UNIT-2 : Advance Web Development (ExpressJS)

// Create an Express application

const app = express();

// Define a route to handle requests and set a custom response status

app.get('/status', (req, res) => {

// Set the HTTP status code to 404

res.status(404).send('Resource not found');

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Redirecting to a New URL

Here's an example of how to implement redirection to a new URL in an Express.js application:

Example:

Copy Code// Require the Express module

const express = require('express');

// Create an Express application

const app = express();

// Define a route that redirects to a new URL

app.get('/redirect', (req, res) => {

// Specify the URL to which the response should redirect

res.redirect('https://www.example.com');

});

// Start the server

app.listen(3000, () => {

24
UNIT-2 : Advance Web Development (ExpressJS)

console.log('Server is running on http://localhost:3000');

});

Rendering Views with Template Engines

Here's an example of how you can use the res.render() method in Express.js to render views using a
template engine:

Example:

Copy Code// Require Express and path modules

const express = require('express');

const path = require('path');

// Create an Express application

const app = express();

// Set the view engine to ejs and specify the views directory

app.set('view engine', 'ejs');

app.set('views', path.join(__dirname, 'views'));

// Define a route to render an ejs view

app.get('/render', (req, res) => {

// Render the 'index' view with a title variable

res.render('index', { title: 'Express Render Example' });

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

Sending a File Response

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:

Copy Code// Require Express and path modules

25
UNIT-2 : Advance Web Development (ExpressJS)

const express = require('express');

const path = require('path');

// Create an Express application

const app = express();

// Define a route to send a file

app.get('/file', (req, res) => {

// Set the path to the file

const filePath = path.join(__dirname, 'example.pdf');

// Send the file at the specified path

res.sendFile(filePath, function(err) {

if (err) {

console.log('Error sending file:', err);

res.status(500).send('Error sending file');

} else {

console.log('File sent successfully');

});

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

ExpressJS - Error Handling

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)

app.use(function(err, req, res, next) {

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

var express = require('express');

var app = express();

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

//Create an error and pass it to the next function

var err = new Error("Something went wrong");

next(err);

});

/*

* other route handlers and middleware here

* ....

*/

//An error handling middleware

app.use(function(err, req, res, next) {

res.status(500);

res.send("Oops, something went wrong.")

});

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.

ExpressJS - Form Data


Forms are an integral part of the web. Almost every website we visit offers us forms that submit or
fetch some information for us. To get started with forms, we will first install the body-parser(for
parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware.

To install the body-parser and multer, go to your terminal and use −

E:\Dev\hello-world>npm install --save body-parser multer

added 18 packages, and audited 128 packages in 1s

20 packages are looking for funding

run `npm fund` for details

found 0 vulnerabilities

Replace your index.js file contents with the following code −

index.js

var express = require('express');

var bodyParser = require('body-parser');

var multer = require('multer');

var upload = multer();

28
UNIT-2 : Advance Web Development (ExpressJS)

var app = express();

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

res.render('form');

});

app.set('view engine', 'pug');

app.set('views', './views');

// for parsing application/json

app.use(bodyParser.json());

// for parsing application/xwww-

app.use(bodyParser.urlencoded({ extended: true }));

//form-urlencoded

// for parsing multipart/form-data

app.use(upload.array());

app.use(express.static('public'));

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

console.log(req.body);

res.send("recieved your request!");

});

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)

title Form Tester

body

form(action = "/", method = "POST")

div

label(for = "say") Say:

input(name = "say" value = "Hi")

br

div

label(for = "to") To:

input(name = "to" value = "Express forms")

br

button(type = "submit") Send my greetings

Run your server using the following.

E:\Dev\hello-world>nodemon index.js

[nodemon] 3.1.9

[nodemon] to restart at any time, enter `rs`

[nodemon] watching path(s): *.*

[nodemon] watching extensions: js,mjs,cjs,json

[nodemon] starting `node index.js`

Now go to localhost:3000/ and fill the form as you like, and submit it.

The following response will be displayed −

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

[nodemon] to restart at any time, enter `rs`

[nodemon] watching path(s): *.*

[nodemon] watching extensions: js,mjs,cjs,json

[nodemon] starting `node index.js`

{ say: 'Hi', to: 'Express forms' }

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.

CORS Policy in Express.js


CORS (Cross-Origin Resource Sharing) is a mechanism that allows resources on a web page to be
requested from another domain outside the domain from which the resource originated. Here's how
to implement it in Express.js:

Basic CORS Setup

javascript

const express = require('express');

const cors = require('cors');

31
UNIT-2 : Advance Web Development (ExpressJS)

const app = express();

// Enable CORS for all routes

app.use(cors());

app.listen(3000, () => {

console.log('Server running on port 3000');

});

Custom CORS Configuration

For more control, you can customize your CORS settings:

javascript

const corsOptions = {

origin: 'https://example.com', // Specific domain allowed

methods: ['GET', 'POST'], // Allowed HTTP methods

allowedHeaders: ['Content-Type', 'Authorization'], // Allowed headers

credentials: true, // Allow cookies

maxAge: 86400 // How long the results of a preflight request can be cached (in seconds)

};

app.use(cors(corsOptions));

Route-Specific CORS

You can also apply CORS to specific routes:

javascript

// Enable CORS for all routes

app.use(cors());

// Custom CORS for a specific route

app.get('/api/data', cors(corsOptions), (req, res) => {

res.json({ message: 'This route has custom CORS settings' });

});

Dynamic Origin Configuration

32
UNIT-2 : Advance Web Development (ExpressJS)

You can dynamically allow origins based on your requirements:

javascript

const corsOptions = {

origin: function (origin, callback) {

const allowedOrigins = ['https://example.com', 'https://subdomain.example.com'];

if (!origin || allowedOrigins.indexOf(origin) !== -1) {

callback(null, true);

} else {

callback(new Error('Not allowed by CORS'));

};

app.use(cors(corsOptions));

What is Body Parser?


Body parser extracts the entire body portion of an incoming request stream and makes it available on
req.body. Without it, you cannot access form data or JSON payloads sent to your server.

Setting Up Body Parser

Express 4.16.0 and higher includes body parser functionality built-in:

javascript

const express = require('express');

const app = express();

// Parse JSON bodies

app.use(express.json());

// Parse URL-encoded bodies (form data)

app.use(express.urlencoded({ extended: true }));

For older Express versions, install the separate package:

bash

npm install body-parser

33
UNIT-2 : Advance Web Development (ExpressJS)

Then use it:

javascript

const express = require('express');

const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

Basic Usage Example

javascript

const express = require('express');

const app = express();

// Middleware setup

app.use(express.json());

app.use(express.urlencoded({ extended: true }));

// GET route - no body parser needed

app.get('/', (req, res) => {

res.send('Hello World!');

});

// POST route - body parser makes form data accessible

app.post('/login', (req, res) => {

const username = req.body.username;

const password = req.body.password;

console.log(`User attempting login: ${username}`);

// Process login data here

res.send(`Login attempt received for ${username}`);

34
UNIT-2 : Advance Web Development (ExpressJS)

});

app.listen(3000, () => {

console.log('Server running on port 3000');

});

Common Options

• extended: true - allows rich objects and arrays to be encoded into the URL-encoded format

• limit: '1mb' - controls the maximum request body size

• type: 'application/json' - determines which media type the middleware will parse

Testing Your Setup

Use a simple HTML form:

html

<form action="/login" method="post">

<input type="text" name="username" placeholder="Username">

<input type="password" name="password" placeholder="Password">

<button type="submit">Login</button>

</form>

Or test with a tool like Postman by sending a POST request with a JSON body.

Handling Different Data Types

Body parser can handle various data formats:

javascript

// For JSON

app.use(express.json());

// For form data

app.use(express.urlencoded({ extended: true }));

// For raw data (if needed)

app.use(express.raw());

// For text data (if needed)

35
UNIT-2 : Advance Web Development (ExpressJS)

app.use(express.text());

Setting Up Your MERN Stack Environment

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:

1. Install Node.js and NPM

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

3. Create Your Project Directory

mkdir my-mern-app

cd my-mern-app

4. Initialize Your Node.js Application

npm init -y

5. Install Express.js

npm install express

6. Set Up React

npx create-react-app client

7. Install Mongoose

npm install mongoose

8. Install Additional Packages

npm install cors dotenv body-parser

9. Create Your Server File

Create a file named server.js in your project root and set up a basic Express server:

const express = require('express');

const mongoose = require('mongoose');

const app = express();

const PORT = process.env.PORT || 5000;

36
UNIT-2 : Advance Web Development (ExpressJS)

app.listen(PORT, () => {

console.log(`Server is running on port ${PORT}`);

});

10. Connect to MongoDB

Use Mongoose to connect to your MongoDB database:

mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true,


useUnifiedTopology: true })

.then(() => console.log('MongoDB connected'))

.catch(err => console.log(err));

37

You might also like