HomeTutorsContact

How to redirect http url request in server?

By Gulshan Saini
Published in NodeJS
December 18, 2020
1 min read

Let’s say you have a single GET route i.e. /ping defined inside a simple HTTP server written in expressjs.

Due to some business requirement, you want to redirect all traffic coming on /ping to /healthcheck.

Example:

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

// routes
app.get('/ping', (req,res) => { res.send('I am alive') });

const listener = app.listen(process.env.PORT, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

So how do we achieve this?

To achieve this we are going to introduce a middleware.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Our middleware is going to check if any request is coming on /ping route, just redirect it to /healthcheck.

So here is our clever middleware function

app.use(function (req, res, next) {
  if(req.url==='/ping'){
    res.redirect('/healthcheck')
  }
  next()
});

We need to introduce this middleware in our expressjs server before any routes like this

app.use(function (req, res, next) {
  if(req.url==='/ping'){
    res.redirect('/healthcheck')
  }
  next()
});

// routes
app.get('/healthcheck', (req,res) => { res.send('I am alive') });

After this we also need to update the route so that it can handle request coming on /healthcheck url.

app.get('/healthcheck', (req,res) => { res.send('I am alive') });

Updated Code

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

app.use(function (req, res, next) {
  if(req.url==='/ping'){
    res.redirect('/healthcheck')
  }
  next()
});
// routes
app.get('/healthcheck', (req,res) => { res.send('I am alive') });

// listen for requests :)
const listener = app.listen(process.env.PORT, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

Now if you make a GET request to /ping URL, it will automatically redirect to /healthcheck. And, if somebody makes a direct request to /healthcheck he is still served with the same response i.e. I am alive


Tags

#koa#expressjs
Previous Article
What is rel noopener?

Related Posts

NodeJS
(Solved) How to fix UnauthorizedError invalid algorithm?
August 30, 2020
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Flutter
JavaScript
NextJS
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media