Redirect to another page URL in Node.js (not explicitly or in another form)

I want to redirect a user from one page to another page in Node.js (plain Node.js)

Real life scenario: Afer signup (example.com/sigup), after successful registration I want to redirect users to the login page (example.com/login).

if (signUpSuccessful(request, response)) { // I want to redirect to "/login" using request / response parameters. } 
+8
source share
3 answers

It's simple:

 if (signUpSuccessful(request, response)) { response.statusCode = 302; response.setHeader("Location", "/login"); response.end(); } 

This will redirect the user to the URL /login with the status 302 Found and complete the response. Make sure you have not called response.write() yet, otherwise an exception will be thrown.

+11
source share

The easiest way to do this is: 302 status code and location field with destination URL.

HTTP Response Status Code 302 Found - This is the usual way to perform a redirect.

An HTTP response with this status code will optionally provide a URL in the Location header field. User Agent (for example, a web browser) is invited by the answer with this code to make a second, otherwise identical request, to the new specified URL in the "Location" field. The HTTP / 1.0 specification (RFC 1945) defines this code and gives it a description of the phrase "Moved Temporarily".

Source: Wikipedia

 res.statusCode = 302; res.setHeader("Location", '/login'); res.end(); 
+4
source share

The simplest way:

 res.redirect(307, '/login'); 

Find more information in the reply to this post.

0
source share

All Articles