To redirect a user in a Node.js Express application, you can use the redirect
method provided by the Express framework. Here’s a full example demonstrating how to redirect a user from one route to another:
Step 1: Set up a new Node.js project and install the Express package.
Create a new directory for your project, navigate to it in a terminal, and run the following commands:
npm init -y
npm i express
Step 2: Create an app.js
file and set up a basic Express application.
Inside the project directory, create a new file named app.js
and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const express = require('express'); const app = express(); // Define a route app.get('/home', (req, res) => { res.send('Welcome to the home page'); }); // Redirect route app.get('/redirect', (req, res) => { res.redirect('/home'); }); // Start the server app.listen(3000, () => { console.log('Server is running on port 3000'); }); |
In the above code, we import the Express package and create an instance of the Express application. We define a route /home
that sends a simple message. Then, we define a /redirect
route that uses the redirect
method to redirect the user to the /home
route. Finally, we start the server on port 3000 and log a message to indicate that the server is running.
Step 3: Start the server and test the redirection.
Save the app.js
file, go to the project directory in a terminal, and run the following command: