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.
By the end of this tutorial, you will understand:
Before you begin, you should have a basic understanding of:
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.
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)
.
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');
});
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.
In this tutorial, you learned about:
res.redirect()
app.use()
Here are a couple of exercises to practice what you've learned:
Remember, the best way to learn is by doing, so make sure to practice these exercises on your own!
Continue exploring Express.js by learning about other important topics like routing, middleware, and template engines.