javascript

How to redirect with express


In this article, you will learn about how to redirect with express.

Express is a popular backend web application framework for nodejs. It is mainly designed for building web applications and APIs. Express lets you write server-side logic for web and mobile applications. You can easily redirect a URL in express to do so you have to use res.redirect() function which is provided by express itself.

This res.redirect() function accepts two parameters one is status which refers to HTTP status code and another one is PATH which describes the PATH you want to redirect in. Let’s see an example:

const express = require('express');
const app = express();

app.get('/', function(req, res){
    res.redirect('/registration'); // Redirected to registration Page
});
  
app.get('/registration', function(req, res){
    res.send("Redirected to registration Page");
});
 
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`App is running on port ${PORT}...`);
});

You can also set the status code in the redirect function. By default, the status code is 302 which means FOUND. But you can set the status code explicitly. Let’s see an example with the status code.

const express = require('express');
const app = express();

app.get('/', function(req, res){
    res.redirect(301,'/registration'); // Redirected to registration Page
});

app.get('/registration', function(req, res){
    res.send("Redirected to registration Page");
});
 
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`App is running on port ${PORT}...`);
});

Here, the first parameter expects a numeric value and the status code 301 indicates that the URL has permanently changed.

This is all about redirect with express and you may learn how to redirect with express by using res.redirect().


Share on social media

//