June 5, 2024

ExpressJS Redirect Using res.redirect()

In a web application you may have many pages and based on some event (like clicking submit button) you want the user to move from one page to another. To do that redirect is used and that's the topic of this article how to redirect from one URL to another or from one path to another in Express.

Redirect in ExpressJS

In ExpressJS response.redirect() method is used to redirect user to another URL.

response.redirect() syntax
res.redirect(status, path)
  • path- Redirects to the URL derived from the specified path
  • status- An optional parameter to send a HTTP status code. Default status code is "302" (Found).

res.redirect() usage examples

1. Redirects can be a fully-qualified URL for redirecting to a different site:

res.redirect('http://knpcode.com')

2. Redirects can be relative to the root of the host name. For example, if the application is on http://knpcode.com/admin/post/new, the following would redirect to the URL http://knpcode.com/admin:

res.redirect('/admin')

3. Redirects can be relative to the current URL. For example, from http://knpcode.com/admin/ (path with a trailing slash), the following would redirect to the URL http://knpcode.com/admin/post/new.

res.redirect('post/new')

4. You can also use '..' which means one level up for redirect. If you were on http://knpcode.com/admin/post/new, the following would redirect to http://knpcode.com/admin/post:

res.redirect('..')

res.redirect example in Express

1. This example shows redirect to another path.

const express = require('express');

const app = express();
const port = 3000;

app.get('/', function(req, res){
    console.log('Redirecting to home page...');
    // redirect to another path
    res.redirect('/home');
})


app.get('/home', function(req, res){
    res.send("<h3>Welcome to my site</h3>");
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

If you run the application and access URL http://localhost:3000 it should redirect you to http://localhost:3000/home

2. Redirect to another fully qualified URL

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

app.get('/', function(req, res){
    console.log('Redirecting to another URL...');
    // redirect to another URL
    res.redirect('http://knpcode.com');
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

That's all for the topic ExpressJS Redirect Using res.redirect(). If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment