Introduction to ExpressJS
When developers transition from client-side JavaScript to server-side development with Node.js, the first experience with the native http module can sometimes be a bit cumbersome. Even though the module is quite powerful, using the native module of Node.js to develop any kind of scalable application requires a lot of “boilerplate” code for simple operations like routing, handling cookies, and session management.
This is where Express.js comes in. Express.js, or Express, is the most popular, minimal, and flexible web application framework for Node.js, offering the best set of features for web and mobile applications. Dive deep into ExpressJS using our MEAN Stack Certification Training.
1. Defining the Framework: What is Express JS?
Express JS is essentially a layer on top of the Node.js HTTP server. Express JS doesn’t hide the functionality of Node.js; rather, it extends the functionality with some useful functionality that makes the organization of the logic of your application quite easy.
Key Characteristics:
- Minimalist: It gives you a thin layer of basic web application features without obscuring Node.js features.
- Unforce: Unlike other frameworks such as Angular or Django, Express.js will not dictate to you how you should organize your files or what is ‘right’ and ‘wrong’.
- Middleware-Based: The heart and soul of Express is its middleware, which allows you to run code, modify the request/response objects, and end the request-response cycle.
- Performance: As it is so minimalist, it preserves the legendary speed and asynchronous nature of Node.js.
2. Core Components of Express.js
To understand what Express.js is, one needs to look at its four pillars: Routing, Middleware, Request/Response objects, and Template Engines.
A. Routing
Routing is essentially how an application’s endpoints (URIs) will respond to client requests. One can declare routing using the following methods of the Express app object.
- GET: It is used to retrieve data from the server.
- POST: It is used to submit data to be processed by the server.
- PUT: It is used to update an existing resource.
- DELETE: It is used to remove a resource.
B. Middleware
Middleware is an example of a function that is given access to the request object (req), the response object (res), and the next middleware function in the chain of calls to the next function in the application’s request-response cycle (usually denoted by a variable named next).
C. Request and Response Objects
- req (Request): This object holds information about the HTTP request.
- res (Response): This object holds information about how we can send information back to the client.
Find our MEAN Stack tutorial for beginners to learn more.
3. Getting Started: A Basic Example
To understand what Express is, let’s first consider how simple it is to start up an Express server.
Installation
Before we begin, you must first have Node.js installed. Then:
npm init -y
npm install express
The Hello World Server
Create a file with a name, app.js
JavaScript
const express = require(‘express’);
const app = express();
const port = 3000;
// Defining a route
app.get(‘/’, (req, res) => {
res.send(‘Hello World! You are using Express.’);
});
// Starting the server
app.listen(port, () => {
System.out.println(`Server running at http://localhost:${port}`);
});
4. Advanced Features and Middleware
Express excels in the “Plug and Play” environment.
Built-in Middleware
In the latest version of Express, namely 4.x, there are built-in middleware modules for handling JSON and URL-encoded data:
app.use(express.json()); // Parses incoming JSON requests
app.use(express.static(‘public’)); // Serves static files like images/CSS
Third-Party Middleware
There are thousands of third-party packages available for Express.js:
- morgan: For logging HTTP requests.
- cors: For enabling CORS.
- helmet: For securing your apps by setting various headers.
5. Why Choose Express.js?
The answer to the question of what is express.js in the context of the modern industry is “the backbone of the MEAN/MERN stack.”
Key Benefits:
- Development Speed: What would require 50 lines of code in pure Node.js can be done in 5-10 lines of code in Express.
- Application Scalability: Express can be easily integrated with databases like MongoDB, PostgreSQL, and MySQL.
- Community Support: Since Express has been the industry standard since 2010, you will find the answer to almost any problem on Stack Overflow.
- Routing Simplicity: Complex routing is easily handled using express.Router.
Propel your career with our MEAN Stack interview questions and answers.
Creating a RESTful API with Express.js
To understand Express.js, it is important to understand how it works by creating a structured API. In this case, we are going to create a simple “Book Store” API, which will be able to handle the CRUD operations.
1. Setting Up the Project
It is important to have a folder set up. We are going to use an array to mimic the database.
JavaScript
const express = require(‘express’);
const app = express();
// Middleware to parse JSON bodies
app.use(express.json());
let books = [
{ id: 1, title: “The Great Gatsby”, author: “F. Scott Fitzgerald” },
{ id: 2, title: “1984”, author: “George Orwell” }
];
2. Implementing CRUD Routes
READ (GET)
We can retrieve all books or a book by its ID.
// Get all books
app.get(‘/api/books’, (req, res) => {
res.json(books);
});
// Get a single book by ID
app.get(‘/api/books/:id’, (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).send(‘Book not found.’);
res.json(book);
});
CREATE (POST)
We can add a new book to our “database” using ‘app.post.’
app.post(‘/api/books’, (req, res) => {
const newBook = {
id: books.length + 1,
title: req.body.title,
author: req.body.author
};
books.push(newBook);
res.status(201).json(newBook);
});
UPDATE (PUT)
This is used to update an existing record.
app.put(‘/api/books/:id’, (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).send(‘Book not found.’);
book.title = req.body.title;
book.author = req.body.author;
res.json(book);
});
DELETE (DELETE)
This can be used to remove a record from our list.
app.delete(‘/api/books/:id’, (req, res) => {
const bookIndex = books.findIndex(b => b.id === parseInt(req.params.id));
if (bookIndex === -1) return res.status(404).send(‘Book not found.’);
const deletedBook = books.splice(bookIndex, 1);
res.json(deletedBook);
});
Get more MEAN Stack project ideas to learn through real-time examples.
3. Error Handling Middleware
One of the most powerful features of what is express.js is its error handling. Instead of using try-catch blocks all over the place, we can have a special middleware at the end of our script.
JavaScript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send(‘Something went wrong on our end!’);
});
app.listen(3000, () => console.log(‘API listening on port 3000…’));
Key Concepts in ExpressJS
| Concept | Description |
| req.params | Used to capture dynamic values in the URL (like :id). |
| req.body | Used to access data sent in a POST or PUT request (requires express.json()). |
| Status Codes | 200 (OK), 201 (Created), 404 (Not Found), 500 (Server Error). |
| res.json() | Automatically sets the Content-Type header to application/json. |
Conclusion
Express JS is the standard web framework for Node JS that helps simplify the server-side logic of your application. Express JS acts as a bridge between the complexities of the HTTP protocol and the business logic of your application. By using Express, we did not have to manually parse the URL string to retrieve IDs and manually handle the data stream for POST requests. This “thin layer” over Node.js makes our code easy to read and maintain. Are you building a simple REST API or a full-stack web application with React or Vue? Learn more about Express.js in our software training institute in Chennai.
