Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to different page url in Node.js (Not in express or other frameworks)

Tags:

node.js

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

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

if (signUpSuccessful(request, response)) {    
    // I want to redirect to "/login" using request / response parameters.
}
like image 871
Manish Kumar Avatar asked Jul 17 '13 16:07

Manish Kumar


People also ask

How do I redirect a specific URL in node?

The res. redirect() is a URL utility function which helps to redirect the web pages according to the specified paths. 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.

Is Express the only framework for NodeJS?

You don't need Express to create a basic HTTP server with Node. js. You can do that using the built in http module: const http = require("http"); const server = http.


2 Answers

It's simple:

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

This will redirect your user to the /login URL with an 302 Found status and finish the response. Be sure that you haven't called response.write() before, otherwise an exception will be thrown.

like image 127
gustavohenke Avatar answered Oct 05 '22 23:10

gustavohenke


Simplest way to do it is by using a 302 status code and a location field with the target URL.

The HTTP response status code 302 Found is a common way of performing a redirection.

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

Source: Wikipedia

res.statusCode = 302;
res.setHeader("Location", '/login');
res.end();
like image 32
Split Your Infinity Avatar answered Oct 05 '22 23:10

Split Your Infinity