Skip to main content

Command Palette

Search for a command to run...

How To Redirect The User To Another Page When Using Express

Published
1 min read
How To Redirect The User To Another Page When Using Express
E

I'm a full-stack web developer who loves building new projects and learning new things

It might not show from my posts, but I'm also quite funny.

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

More from this blog

Javasper

50 posts

I'm a full stack software developer who loves to building new projects and solving difficult problems.

It might not be obvious from my posts, but I'm actually quite funny.