Different functions of the app object

1. Defining Routes with “app”

The `app` object is to define routes for handling different HTTP methods and paths. Routes are defined using methods like GET, POST, PUT and DELETE.

Here’s a simple example:

// Handling GET requests to the root path "/"
app.get('/', (req, res) => {
res.send('Hello, World!');
});

2. Middleware with “app”

Middleware functions are functions that have access to the request (`req`), response (`res`), and the next middleware function in the application’s request-response cycle. The `app` object is used to apply middleware to your application.

Syntax:

// Logger middleware
const loggerMiddleware = (req, res, next) => {
console.log(`Received a ${req.method} request to ${req.path}`);
next();
};

// Applying the logger middleware to all routes
app.use(loggerMiddleware);

3. Setting Configuration with “app”

The `app` object allows you to configure various settings for your application, such as the view engine, port number, and more.

Syntax:

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

How to use the app object in Express ?

In Node and Express, the app object has an important role as it is used to define routes and middleware, and handling HTTP requests and responses. In this article, we’ll explore the various aspects of the `app` object and how it can be effectively used in Express applications.

Similar Reads

Prerequisites

Node.js and NPM should be installed. Basics of Express JS...

Different functions of the app object:

1. Defining Routes with “app”...

Steps to create a sample Express app.

Step 1: Create a directory for the application...