Open In App

How to handle redirects in Express JS?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Express JS uses redirects to send users from one URL to another. This can be done for various reasons, such as handling outdated URLs or guiding users through a process. In ExpressJS, you define routes and use them to direct users to the desired URL. It’s a way to keep your application organized and user-friendly.

Steps to Handle Redirects in Express JS:

Step 1: Import the express: Install the express package in your app using the following command.

npm install express

Step 2: Create an express application: To create an express application by calling express() function i.e.

const app = express()

Step 3: Define the routes: Use ExpressJS to define routes in your application using methods like app.get() or app.post().

app.get('/old-page', (req, res) => {
res.redirect('/new-page');
});
app.post('/submit-form', (req, res) => {
// Perform some processing...

res.redirect('/thank-you');
});

Handling redirects in ExpressJS involves creating an Express application, defining routes that specify URL paths and corresponding route handlers, and using the res.redirect() method within route handlers to redirect users to different URLs. Finally, we start the server to listen for incoming requests on a specified port.

Example: Below is the example to handle redirects in ExpressJS.

Javascript




//server.js
 
const express = require('express');
const app = express();
 
// To define a route to handle GET requests to '/old-url'
app.get('/old-url', (req, res) => {
    // To Redirect users to '/new-url'
    res.redirect('/new-url');
});
 
/*
  To define a route to handle POST
  requests to '/submit-form' */
app.post('/submit-form', (req, res) => {
    // Process form submission...
 
    /* To redirect users to
      '/thankyou' after processing the form */
    res.redirect('/thankyou');
});
 
// To define a route for the new URL '/new-url'
app.get('/new-url', (req, res) => {
    res.send('This is the new URL');
});
 
// To Define a thankyou route to redirect.
app.get('/thankyou', (req, res) => {
    res.send('Thank you for submitting the form!');
});
 
// Start the server
const port = 3000;
app.listen(port,
    () => {
        console.log(`Server is running on http://localhost:${port}`);
    });


Start the server using the following command.

node server.js

Output:

gfg23

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads