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:

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

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

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

Updated Code

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?

Gulshan Saini

Fullstack Developer

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

(Solved) How to fix UnauthorizedError invalid algorithm?

August 30, 2020
1 min
© 2021, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media