Implementing routes, middleware, and error handling with Express.js

Express.js is a flexible and powerful web application framework for Node.js that enables developers to build robust and scalable web servers. It provides a simple yet effective way to handle various aspects of web development, including routing, middleware, and error handling. In this article, we will explore how to implement these features using Express.js.

Routing

Routing is a fundamental aspect of any web application, as it defines how the server responds to client requests. Express.js makes routing easy and intuitive by allowing developers to define routes based on HTTP methods and URL patterns. Let's see how it works:

const express = require('express');
const app = express();

// Define a GET route
app.get('/hello', (req, res) => {
  res.send('Hello, world!');
});

// Define a POST route
app.post('/users', (req, res) => {
  // Create a new user
});

// Define a dynamic route
app.get('/users/:id', (req, res) => {
  const id = req.params.id;
  // Fetch user based on the id
});

// Define a default route
app.use((req, res) => {
  res.status(404).send('Page not found');
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In the above code snippet, we define different routes using app.get(), app.post(), and app.use() methods. The :id in the dynamic route represents a placeholder that can match any value in the actual URL. Express.js automatically parses the URL parameters and makes them available in the req.params object.

Middleware

Middleware functions in Express.js provide a way to execute code before or after the route handlers. They can be used for tasks such as request preprocessing, authentication, logging, etc. Express.js offers a wide range of middleware functions, and developers can also create custom middleware. Let's see how to use middleware in Express.js:

const express = require('express');
const app = express();

// Built-in middleware for serving static files
app.use(express.static('public'));

// Custom middleware
app.use((req, res, next) => {
  console.log('Request received at:', req.url);
  next();
});

// Route handler
app.get('/hello', (req, res) => {
  res.send('Hello, world!');
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In the code above, we use the built-in express.static() middleware to serve static files from the public directory. The custom middleware function logs the request URL before passing control to the next middleware or route handler using the next() function.

Error handling

Error handling is a critical aspect of any application. Express.js simplifies error handling through a mechanism called error middleware. Error middleware functions have an additional err parameter, allowing developers to handle errors in a centralized manner. Here's an example:

const express = require('express');
const app = express();

// Route handler
app.get('/hello', (req, res) => {
  throw new Error('Something went wrong');
});

// Error middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Internal Server Error');
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In the above code snippet, we intentionally throw an error within the route handler to simulate an error scenario. The error middleware function logs the error stack trace and sends a generic error response with a status code of 500.

Express.js provides an elegant and flexible way to handle routes, use middleware, and deal with errors. It's a powerful framework that simplifies web development and enables developers to focus on building great applications. Happy coding!


noob to master © copyleft