ExpressJS - redirect method

ExpressJS - redirect method

res.redirect()

·

2 min read

Have you ever wondered, when ever you are not logged-in to a website and you try to request a service that is only possible if you log-in then you get redirected to log-in page.

Turns out, it is just a single line of code that does this redirection in ExpressJS, if the backend of that website is written using NodeJS.

Lets have a look at the code first.

import express from 'express'
const app = express()  

app.get('/about', (req, res) =>{
    //check what ever logic you want
    // res.redirect([status,] path)
    res.redirect('/')

    //we can also redirect to the external website
    // res.redirect('https://www.google.com')
})

Below is the working of the redirect method

By definition in the documentation of ExpressJS, we can also mention the status code in the redirect method as the 1st parameter. If you don't specify the satus code then it defaults to “302 Found”.

res.redirect([status,] path) // status is optional
res.redirect(301, 'http://example.com')

If you are a Linux OS based user I am sure you must have used ".." to go back to the parent directory, we can so the same here.

res.redirect('..')

This is all you need to know about redirect method in ExpressJS if your are a beginner, if you want to learn more about it head to express-redirect_method

Until next time happy and productive learning. Bye Bye