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


Question

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').

1
65
7/2/2017 7:39:38 PM

Accepted Answer

response.writeHead(301,
  {Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();
105
7/6/2012 3:55:12 AM

http.get('*',function(req,res){  
    res.redirect('http://mydomain.com'+req.url)
})

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon