ExpressJS is a fast and minimal web application framework that is built on top of NodeJS. It provides a robust set of features such as handling HTTP requests, implementing middleware, routing etc. which can be utilized to build dynamic web applications, mobile applications and implement APIs.
It is a thin, lightweight and flexible framework core web application features. Additional features can be added through the use of Express middleware modules. In this article, we will explore how Express works.
Prerequisites: Installing Express:Step 1: Initialize and Node.js project
mkdir express-app cd express-app npm init -y Step 2: Install Express using npm
npm install express  To add express to a pre-existing node project,
Step 3: Add express to the dependencies in package.json
 package.json Step 4: Install all the dependencies using `npm install`
 npm install Usage of Express:Depending on an application’s requirements, Express.js can be used in various ways such as:
- Creating a basic server
- Implementing middleware
- Routing
- Handling HTTP requests
- Integrating with databases.
Creating a Basic ServerTo create an Express server, initialize a node.js project and install express following the installation guide. Then create an app instance and define a port for the server to listen on as show in the following code:
JavaScript
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Server is online!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
 basic Express server To run the server use the command:
`node <filename>.js` Implementing middlewareMiddleware function are functions that have access to the request object and are executed before the requests are handled. Middleware functions can be added using `app.use(middleware)`
JavaScript
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Middleware function executed');
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
 adding middleware The middleware function is executed every time a request is sent to the server.
Creating RoutesRoutes can be defined as endpoints of an application that are utilized to describe how the server responds to client’s requests. routes can be create using `app.[HTTP Method](<routename>, handler function)`. example:
JavaScript
const express = require('express');
const app = express();
app.get('/about', (req, res) => {
console.log('accessed about us page');
res.send('About Page');
});
app.get('/contact', (req, res) => {
console.log('accessed contact us page');
res.send('Contact Page');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Here when a request is sent to `http:localhost:3000/about` the handler function corresponding to the route is executed.
 creating routes Handling HTTP methodsExpress allows you to handle various HTTP methods like GET, POST, PUT, DELETE, etc. as follows:
JavaScript
const express = require('express');
const app = express();
app.post('/submit', (req, res) => {
res.send('Form Submitted');
});
app.put('/update', (req, res) => {
res.send('Data Updated');
});
app.delete('/delete', (req, res) => {
res.send('Data Deleted');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
 handling HTTP methods Functioning of these routes be tested using dev tools such as postman or using a browser.
Integrating with DatabasesExpress be integrated with databased such as MongoDB, MySQL, PostgreSQL to store and perform operations on data.
JavaScript
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
mongoose.connect('mongodb://localhost:27017/mydatabase');
const Schema = mongoose.Schema;
const StudentSchema = new Schema({
name: String
});
const Student = mongoose.model('Student', StudentSchema);
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/students', async (req, res) => {
try {
const students = await Student.find({}, 'name');
res.json(students);
} catch (error) {
res.status(500).send(error);
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
 fetching data from MongoDB Why Use Express?- Minimalist Framework: Express does not enforce a particular way of structuring your application.
- Robust Routing: It provides a robust routing mechanism for handling different HTTP requests.
- Middleware Support: Allows for easy integration of middleware to process requests and responses.
- Performance: Built on top of Node.js, it uses its asynchronous, non-blocking nature for high performance.
- Community and Ecosystem: A vast and active community contributes to a rich ecosystem of middleware and plugins.
ConclusionExpress.js simplifies the process of building web applications by providing a powerful framework that handles routing, middleware, HTTP methods, and integrates well with databases
Frequently Asked Questions (FAQs)How does Express handle multiple requests?Express handles multiple requests asynchronously by default. Each incoming request is processed independently. And callbacks or promises are utilized to handle the asynchronous operations
How can I handle errors in Express.js applications?Errors in Express.js servers can be handled by either using try-catch blocks in the request handler’s logic or declaring middlewares to handle the error.
How can I handle file uploads in Express.js?File uploads can be handled on Express.js servers using middleware such as ‘multer’ which enables us to handle multipart/form-data, which is typically used for file uploads.
|