How to Get Started with Express.js
Day 41 of 60 : 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.
The app object represents the Express application.
It can be created by calling the express() function and is used to set up and configure various aspects of your server.
Syntax:
const express = require('express');
const app = express();
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}`);
});
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.
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:
Output(Console):
Express.js Routing :
Routing is made from the word route.
It is used to determine the specific behavior of an application.
It specifies how an application responds to a client request to a particular route, URI or path and a specific HTTP request method (GET, POST, etc.).
It can handle different types of HTTP requests
et's take an example to see basic routing.
File: routing_example.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Welcome to JavaTpoint!');
})
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('I am Impossible! ');
})
app.delete('/del_student', function (req, res) {
console.log("Got a DELETE request for /del_student");
res.send('I am Deleted!');
})
app.get('/enrolled_student', function (req, res) {
console.log("Got a GET request for /enrolled_student");
res.send('I am an enrolled student.');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Pattern Matched.');
})
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 see that server is listening.
Now, you can see the result generated by server on the local host http://127.0.0.1:8000
Output:
This is the homepage of the example app.
Note: The Command Prompt will be updated after one successful response.
You can see the different pages by changing routes. 127.0.0.1:8000/enrolled_student
Updated command prompt:
This can read the pattern like abcd, abxcd, ab123cd, and so on.
Next route 127.0.0.1:8000/abcd
Next route 127.0.0.1:8000/ab12345cd
Updated command prompt:
How to handle Route Parameters in Express ?
Express makes it easy to create strong and scalable web applications. One cool thing it can do is handle route parameters, which lets developers build dynamic routes that respond to specific values. In this article, we’ll see different ways to work with route parameters in Express.
Understanding Route Parameters:
In a web address, route parameters are like special slots that grab important values for the server.
We mark these slots with a colon and give them a name in the route.
For example, consider the following route:
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
// Rest of the logic to handle the user with the specified userId
});
In this route, :userId is a route parameter that can capture any value in the URL.
Express automatically parses these parameters and makes them available in the req.params object.
Approach 1: Basic Route Parameter Handling
The simplest way to handle route parameters is by accessing them directly from req.params. You can extract the value of the parameter and use it in your route handler logic.
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
// Rest of the logic to handle the user with the specified userId
});
Approach 2: Optional Route Parameters
Express allows you to define optional parameters in your routes by adding a question mark ? to the parameter name. This means that the parameter is not required for the route to match.
app.get('/products/:productId?', (req, res) => {
const productId = req.params.productId || 'default';
// Logic to handle the product with the specified productId or a default value
});
Approach 3: Multiple Route Parameters
You can define routes with multiple parameters by adding additional colon-prefixed parameters in the route definition.
app.get('/posts/:category/:postId', (req, res) => {
const category = req.params.category;
const postId = req.params.postId;
// Logic to handle the post with the specified category and postId
});
Node.js Query String :
The Query String module used to provides utilities for parsing and formatting URL query strings.
It can be used to convert query string into JSON object and vice-versa.
The Query String is the part of the URL that starts after the question mark(?).
Its purpose is to transmit concise data to the server directly through the URL.
Typically, this data serves as a parameter for querying a database or filtering results.
The query parameter is the variable whose value is passed in the URL in the form of a key-value pair at the end of the URL after a question mark (?).
For example:
www.geeksforgeeks.org?name=abc