Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect user's browser URL to a different page in Nodejs?

In the application I'm trying to write, the main page (http://localhost:8675) has the following form:

<form action='/?joinnew' method='post'>   <button>Start</button> </form> 

Here is the code in server.js:

http.createServer(function(request, response) {   var root = url.parse(request.url).pathname.split('/')[1];   if (root == '') {     var query = url.parse(request.url).search:     if (query == '?joinnew') {       var newRoom = getAvaliableRoomId(); // '8dn1u', 'idjh1', '8jm84', etc.       // redirect the user's web browser to a new url       // ??? How to do.  Need to redirect to 'http://whateverhostthiswillbe:8675/'+newRoom ... }}} 

I would love if there were a way to do it where I didn't have to know the host address, since that could be changing.

The 'http' object is a regular require('http'), NOT require('express').

like image 631
Tanaki Avatar asked Jul 06 '12 03:07

Tanaki


People also ask

How do I redirect a login page in node JS?

session. user = o; res. redirect('/home'); } else{ res. render('/login', { title: 'Hello - Please Login To Your Account' }); } }); } });

How do I redirect a Web page to a specific URL?

Redirecting to another URL with JavaScript is pretty easy, we simply have to change the location property on the window object: window. location = "http://new-website.com"; JavaScript is weird though, there are LOTS of ways to do this.


2 Answers

To effect a redirect, you send a redirect status (301 for permanent redirect, 302 for a "this currently lives on ..." redirect, and 307 for an intentional temporary redirect):

response.writeHead(301, {   Location: `http://whateverhostthiswillbe:8675/${newRoom}` }).end(); 
like image 98
ebohlman Avatar answered Sep 28 '22 02:09

ebohlman


For those who (unlike OP) are using the express lib:

http.get('*',function(req,res){       res.redirect('http://exmple.com'+req.url) }) 
like image 37
David Seholm Avatar answered Sep 28 '22 01:09

David Seholm