How to redirect user's browser URL to a different page in Nodejs?
In Node.js, URL redirection typically involves setting the field in the HTTP response headers and sending the appropriate status code, usually (temporary redirect) or (permanent redirect). This can be implemented using various Node.js frameworks, such as the widely used Express framework. Below are specific methods and examples for implementing URL redirection with Express in different scenarios:1. Using the Express framework for redirectionFirst, ensure that Express is installed in your project:Then, you can set up redirection in your application as follows:In the above code, when a user attempts to access , the server redirects the user to . Here, a 302 temporary redirect is used. If you want to perform a 301 permanent redirect, you can write:2. Implementing redirection in pure Node.js without a frameworkIf you are not using any framework, you can implement redirection using the native Node.js HTTP module:In this example, when a user accesses , the server sets the response status to 302 and adds the header to indicate the new URL, then ends the response, redirecting the user to the new page.ConclusionIn Node.js, implementing redirection is straightforward, whether using the Express framework or the native HTTP module. Redirection is a common technique in web development that effectively guides user flow, handles changes to old URLs, and maintains a good user experience. In practical applications, choose between temporary or permanent redirection based on specific requirements.