How To Redirect The User To Another Page When Using Express

How To Redirect The User To Another Page When Using Express

·

1 min read

When using Express, how do we redirect the user to another page?

All we have to do if we want to send the user to another page is to write something like this:

Syntax

res.redirect("/routename");

Then the user will be redirected to the route with the route name of routename.

In the actual myproject/router/index.js file, here is what our code might look like.

Example

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


router.get("/first", function(req, res, next) {
  res.redirect("/second");
});


router.get("/second", function(req, res, next)
{

res.send("Hello world");

});
module.exports = router;

And if we were to access our page first via localhost:3000/first, we would see:

redirect_1.png