How to redirect back to original URL in Node.js ?
Node.js with the help of Express, supports web page routing. This means that when the client makes different requests, the application is routed to different web pages depending upon the request made and the routing methods defined. To learn more about Node.js routing and the implementation, refer this article.
In this article, we will discuss how to redirect back to original URL in Node.js.
The res.redirect() is a URL utility function which helps to redirect the web pages according to the specified paths.
return res.redirect([status], path)
For the first example we will redirect the user to a specified URL with a different domain. Make sure to install express in your project before running the code.
When the above code is executed using node, we will be redirected to the GeeksforGeeks website when we make request for home route on port 3000.
Other methods: Other than redirecting to a different domain, we have some other methods available to redirect as following.
Domain relative redirect: We can use this method to redirect to a different page under the same domain. For example, if the user is at http://example.com/gfg/post1 , then we can redirect to http://example.com/article by using the following line of code
Pathname relative redirect: We can use this method to redirect to the previous path on the website. For example, if the user is at http://example.com/gfg/post1, then we can redirect to http://example.com/gfg by using the following line of code
Redirecting back to original URL:
After learning about res.redirect() function, we can now discuss how to redirect back to original URL in NodeJS.
We can use this method to redirects the request back to the referrer. If no referrer is present, the request is redirected to “/” route by default.
Let’s suppose we are at ‘/example’ route. On requesting the ‘/redex’ route, we will be automatically redirected to ‘/’ route as defined in the code below