Express.js is a web development framework that simplifies the creation of web applications and APIs in Node.js. Undoubtedly, it is the most popular and widely used framework for building web servers.
Express.js offers a range of features such as routing, middleware, and management of HTTP requests and responses. Moreover, it is a stable, proven, and widely used framework.
However, it is a framework that has been around for quite some time. Therefore, numerous alternatives have emerged, including the native library node:http
, which has improved a lot over time.
However, it remains one of the best alternatives and most widely used. It has a large community and available documentation. Therefore, it is interesting that you at least get to know it and know how to use it.
How to Use Express.js
Installing Express.js
To get started, we need to install Express.js in our project. We can do this using npm (Node Package Manager) with the following command in the terminal:
npm install express
Once installed, we can import Express.js into our code to start building our web server.
const express = require('express');
const app = express();
const PORT = 3000; // Port on which the server will listen
// here we would define the routes
// see below
// Start the server
app.listen(PORT, () => {
console.log(`Express server listening on port ${PORT}`);
});
This is how easy it is to create a web server with Express.js.
Creating Routes with Express.js
One of the standout features of Express.js is its routing system. It allows you to define routes to handle different types of HTTP requests, such as GET, POST, PUT, and DELETE. Next, we will see how to create and handle routes in Express.js.
To define a route in Express.js, we use routing methods such as app.get()
, app.post()
, app.put()
, app.delete()
. These methods take the URL of the route as the first argument and a callback function that will be executed when a request is made to that route.
Example of a GET Route
app.get('/', (req, res) => {
res.send('Hello, world from Express.js!');
});
In this example, we are defining a GET route at the root ('/'
) that responds with the message “Hello, world from Express.js!“.
Example of a POST Route
app.post('/users', (req, res) => {
res.send('User information received and processed');
});
In this POST route, we respond with a message indicating that the user information has been received and processed.
Example of a Dynamic Route
In this dynamic route, we capture any value after /users/
using req.params
. We then respond with the requested user ID.
app.get('/users/:id', (req, res) => {
const { id } = req.params;
res.send(`Requested user with ID: ${id}`);
});
Middleware in Express.js
Express.js also offers middleware, functions that run before reaching the final route. This allows us to perform actions such as validating data, handling errors, or authenticating users before reaching the route handler.
Example of Request Logging Middleware
In this example, each time a request arrives at the server, we log the request URL to the console before continuing to the next function in the middleware chain.
app.use((req, res, next) => {
console.log(`Request received at: ${req.url}`);
next();
});
Example of Error Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong');
});
Here we have an error handling middleware that captures any error that occurs during the processing of a request and sends a 500 error response along with a generic error message.
Complete Example of an Express.js Application
Next, we will see a complete example of an Express.js application that uses routing and middleware:
const express = require('express');
const app = express();
const PORT = 3000;
// Request logging middleware
app.use((req, res, next) => {
console.log(`Request received at: ${req.url}`);
next();
});
// GET route at the root
app.get('/', (req, res) => {
res.send('Hello, world from Express.js!');
});
// POST route for users
app.post('/users', (req, res) => {
res.send('User information received and processed');
});
// Dynamic route for users
app.get('/users/:id', (req, res) => {
const { id } = req.params;
res.send(`Requested user with ID: ${id}`);
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong');
});
// Start the server
app.listen(PORT, () => {
console.log(`Express server listening on port ${PORT}`);
});
This example demonstrates how to create a basic web server with Express.js, define routes to handle different types of HTTP requests, and use middleware to perform additional tasks such as request logging and error handling.
Download the Code
All the code from this post is available for download on Github