Steps to create a sample Express app.

Step 1: Create a directory for the application

mkdir app-object
cd app-object

Step 2: Initializing the app and install the required dependencies.

npm init -y
npm i express

Example: In this sample code we have used various app objects.

Javascript




const express = require("express");
const app = express();
 
// Handling GET requests to the root path "/"
app.get("/", (req, res) => {
    res.send("Hello, World!");
});
 
// Handling POST requests to the "/login" path
app.post("/login", (req, res) => {
    res.send("Login successful!");
});
 
// 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);
 
// Handling GET requests to the "/about" path
app.get("/about", (req, res) => {
    res.send("About Us");
});
 
// Setting the port number
const PORT = process.env.PORT || 3001;
 
// Starting the server
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


Output(Browser):

output when the “localhost:3000/” endpoint is hitted.

Output(Console):

console when server is connected and when the middleware is called



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