Table of Contents
When you want to send your users to another page, you can make use of HTTP redirects.
HTTP redirects come in two types, permanent and temporary.
Permanent redirects use the code 301
and temporary redirects use the code 302
.
In this post, we'll learn how to perform redirects using the popular Node web framework, Express.
How to Redirect on Express
Redirects in Express can only be performed inside routes because you need access to the request and response objects.
Let's define a basic route in Express:
JAVASCRIPTapp.get("/a", (req, res) => {
// do something
});
To redirect users, you need to use the res.redirect
method.
This method takes the new path as a parameter and sends the user to that path.
JAVASCRIPTapp.get("/a", (req, res) => {
res.redirect("/b");
});
When a user visits your web app at the path /a
, they will be redirected to the path /b
.
Keep in mind that this is a temporary redirect.
Here's how to do a permanent redirect:
JAVASCRIPTapp.get("/a", (req, res) => {
res.redirect(301, "/b");
});
Keep in mind that you can also simulate the back button by using the code back
inside the redirect.
JAVASCRIPTapp.get("/a", (req, res) => {
res.redirect("back");
});
Conclusion
In this post, we learned how to perform redirects using Express.
You can perform both permanent and temporary redirects by using the res.redirect
method.
Thanks for reading and happy coding!
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React