Blog Details
MD RAHAT KABIR CHOWDHURY
16 Oct 2024
10 min read
In the realm of modern web development, the quest for simplicity, flexibility, and efficiency often leads developers to powerful frameworks that enhance their productivity. Express.js, a lightweight and popular web framework for Node.js, stands at the forefront of this revolution. Whether you're building APIs or robust server-side applications, Express.js offers the versatility and scalability that developers crave, without unnecessary complexity.
In this blog, we will delve into the essential building blocks of Express.js. From understanding what Express.js is to routing, middleware, and a hands-on guide to building a basic API, this post aims to give you a firm grasp of the basics while preparing you for more advanced topics. Let's dive in!
At its core, Express.js is a minimalist web framework designed for building web applications in Node.js. Known for its unopinionated nature, Express allows developers to structure their applications however they see fit, providing only the essential tools needed to handle requests, route traffic, and build robust web servers.
But what sets Express.js apart from other frameworks?
Express.js is widely celebrated for its:
One of the foundational features of Express.js is its routing mechanism. Routing refers to the process of determining how an application responds to a client request made to a specific endpoint (which is a URL path and a specific HTTP method).
Express.js routes define how your application handles various types of requests, such as GET, POST, PUT, and DELETE. This mechanism allows your application to serve content based on different URLs, making it the backbone of any Express.js app.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Express.js!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this simple example, when a client makes a GET request to the root URL (/
), the server responds with a message saying, "Welcome to Express.js!". This is just scratching the surface—routes can become much more complex with dynamic parameters and middleware.
Dynamic routing allows us to capture values directly from the URL, making it useful for applications that need to pass information via the URL.
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
Here, when you visit /user/123
, the application will return "User ID: 123". The req.params
object contains route parameters, which makes dynamic routing powerful for applications that need to handle variables in the URL.
Middleware functions in Express.js are functions that have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle. These functions can perform a variety of tasks such as modifying request objects, ending the response cycle, or calling the next middleware function in the stack.
Middleware can be thought of as the bridge between a client request and a server's response, giving you unparalleled control over what happens during this lifecycle. There are different types of middleware functions in Express.js, such as:
express.json()
)app.use((req, res, next) => {
console.log('Middleware function is running');
next();
});
In this example, the middleware logs a message for every incoming request before passing control to the next function. The next()
function is crucial because it signals the application to move on to the next middleware or route handler. Without calling next()
, the request will hang, as the response is never sent.
One of the most common middleware functions is express.json()
, which parses incoming requests with JSON payloads. It is essential for APIs that handle POST requests:
Now that we've covered the basics, let's put them into practice by building a simple API using Express.js. For this project, we will create a RESTful API for managing users. We'll handle different HTTP methods like GET, POST, PUT, and DELETE.
First, create a new directory for your project and initialize it with npm init
mkdir express-api
cd express-api
npm init -y
npm install express
Now, create an index.js
file and import Express.
const express = require('express');
const app = express();
app.use(express.json()); // Middleware to parse JSON requests
Let's define routes for handling different user-related operations.
let users = [];
app.get('/users', (req, res) => {
res.json(users);
});
app.post('/users', (req, res) => {
const user = req.body;
users.push(user);
res.status(201).json(user);
});
app.put('/users/:id', (req, res) => {
const { id } = req.params;
const index = users.findIndex(user => user.id === parseInt(id));
if (index !== -1) {
users[index] = req.body;
res.json(users[index]);
} else {
res.status(404).send('User not found');
}
});
app.delete('/users/:id', (req, res) => {
const { id } = req.params;
users = users.filter(user => user.id !== parseInt(id));
res.status(204).send();
});
Finally, let's run our server on port 3000:
app.listen(3000, () => {
console.log('API is running on port 3000');
});
Your basic Express.js API is ready! You can now make GET, POST, PUT, and DELETE requests to /users
.
Express.js offers a flexible and powerful toolkit for building web applications and APIs. With its minimalist approach, Express.js lets you focus on writing application logic while keeping things simple. The routing system provides a clear way to manage HTTP requests, and middleware allows for customization of request and response handling. In this blog, we explored the basics of Express.js, from setting up routing to handling middleware, and finally, building a basic API.
As you continue to explore Express.js, you'll find that it's a highly extensible framework capable of supporting everything from simple REST APIs to complex web applications.
Happy coding!
Don’t worry, we don’t spam!