How to redirect to another page in Node.js
In this tutorial, we will learn about how to redirect a user from one page to another page in the Node.js app.
Note: This tutorial assumes that you are using express framework in node.js.
In node.js, we can use the res.redirect()
method to redirect a user to the another page.
The res.redirect()
method takes the path
as an argument and redirects the user to that specified path.
In this example, we are redirecting a user from ‘/login’ page to ‘/dashboard’ page.
app.get('/login',(req,res)=>{
res.redirect('/dashboard');
})
By default, Node.js express creates a 302
redirect.
If you want to create a permanent redirect, you need to specify a status code 301
like this.
app.get('/lab',(req,res)=>{
res.redirect(301, '/dashboard');
})
If you are redirecting a user to a different website instead of same site, you need to pass a full url of the site like this.
app.get('/lab',(req,res)=>{
res.redirect(301, 'https://google.com/');
})
The path relative redirects are also possible in Node.js, for example if you are on http://localhost:3000/users/sai/edit
the following ..
will redirect to http://localhost:3000/users/sai
.
Here is an example:
res.redirect('..')