Redirecting and Error Handling in Express

Tutorial 5 of 5

1. Introduction

Goal of the Tutorial

In this tutorial, you will learn how to handle redirects and error in Express.js, a popular Node.js web application framework. Redirects are essential for guiding users around your website, while error handling is crucial for preventing your application from crashing when something goes wrong.

Learning Outcomes

By the end of this tutorial, you will understand:

  • The concept of redirects and error handling in Express.js
  • How to implement redirects
  • How to handle errors properly

Prerequisites

Before you begin, you should have a basic understanding of:

  • JavaScript
  • Node.js
  • Express.js

2. Step-by-Step Guide

Redirects

In Express.js, you can redirect the user to a different URL using the response object's res.redirect() function. This function takes one argument, the URL you want to redirect the user to.

Error Handling

In Express.js, errors are handled through middleware. You define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three: (err, req, res, next).

3. Code Examples

Example 1: Redirecting

The following code snippet demonstrates how to implement a simple redirect.

app.get('/old-url', function(req, res) {
  // This will redirect the user from '/old-url' to '/new-url'
  res.redirect('/new-url');
});

Example 2: Basic Error Handling

The following code snippet demonstrates basic error handling in Express.js.

app.use(function(err, req, res, next) {
  console.error(err.stack); // Logs the error stack trace
  res.status(500).send('Something broke!'); // Sends a 500 status and a message to the user
});

In this example, the error-handling middleware is defined using app.use(). If an error is passed to next(), Express will skip all remaining routing and middleware functions and go straight to this error-handling function.

4. Summary

In this tutorial, you learned about:

  • Redirects and how to implement them using res.redirect()
  • Error handling and how to define error-handling middleware using app.use()

5. Practice Exercises

Here are a couple of exercises to practice what you've learned:

  1. Create a route that redirects the user to a different website (for example, Google).
  2. Create an error-handling function that logs the error message instead of the stack trace.

Remember, the best way to learn is by doing, so make sure to practice these exercises on your own!

Next Steps

Continue exploring Express.js by learning about other important topics like routing, middleware, and template engines.

Additional Resources