112

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

Piper
  • 1,266
  • 3
  • 15
  • 26
Tanaki
  • 2,575
  • 6
  • 30
  • 41

6 Answers6

178

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();
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
ebohlman
  • 14,795
  • 5
  • 33
  • 35
  • 14
    In node you can also use `response.writeHead(301, { Location: '/path' });` without the full URL, useful for when you don't know the hostname or protocol beforehand. – adriaan Aug 05 '18 at 11:06
  • 5
    Use code 307 if you don't want chrome to cache the redirect preeminently! In the case listed above, returning 301 will cause browsers to ALWAYS join the same room, even when your server would tell it a different / new room! – Brian Ellis Jul 26 '20 at 22:52
  • Hi What about the reverse re-direction? From a remote url to the localhost pages? – Arj 1411 Sep 16 '21 at 06:26
  • But note that you almost _certainly_ want 302, not 301, so that the browser doesn't hard-cache the redirect. Because if it does, it will insists on using it even if you take that redirect back out. You said it was permanent, and the browser believed you. – Mike 'Pomax' Kamermans Dec 31 '21 at 23:18
128

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

http.get('*',function(req,res){  
    res.redirect('http://exmple.com'+req.url)
})
Klesun
  • 12,280
  • 5
  • 59
  • 52
David Seholm
  • 1,343
  • 1
  • 7
  • 2
36

OP: "I would love if there were a way to do it where I didn't have to know the host address..."

response.writeHead(301, {
  Location: "http" + (request.socket.encrypted ? "s" : "") + "://" + 
    request.headers.host + newRoom
});
response.end();
ciso
  • 2,887
  • 6
  • 33
  • 58
6

In Express you can use

res.redirect('http://example.com');

to redirect user from server.

To include a status code 301 or 302 it can be used

res.redirect(301, 'http://example.com');
Lex
  • 4,749
  • 3
  • 45
  • 66
agravat.in
  • 561
  • 6
  • 14
5

If you are using Express, the cleanest complete answer is this

const express = require('express')
const app     = express()

app.get('*', (req, res) => {
  // REDIRECT goes here
  res.redirect('https://www.YOUR_URL.com/')
})

app.set('port', (process.env.PORT || 3000))
const server = app.listen(app.get('port'), () => {})
vintagexav
  • 2,011
  • 2
  • 18
  • 22
0

You can use res.render() or res.redirect() method to redirect to another page using node.js express

Eg:

var bodyParser = require('body-parser');
var express = require('express');
var navigator = require('web-midi-api');
var app = express();

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render("index");
});

//This reponds a post request for the login page
app.post('/login', function (req, res) {
    console.log("Got a POST request for the login");
    var data = {
        "email": req.body.email,
        "password": req.body.password
    };

    console.log(data);

    //Data insertion code
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("college");
        var query = { email: data.email };
        dbo.collection("user").find(query).toArray(function(err, result) {
            if (err) throw err;
            console.log(result);
            if(result[0].password == data.password)


 res.redirect('dashboard.html');
            else


 res.redirect('login-error.html');
            db.close();
        });
    });

});


// This responds a POST request for the add user
app.post('/insert', function (req, res) {
    console.log("Got a POST request for the add user");

    var data = {
        "first_name" : req.body.firstName,
        "second_name" : req.body.secondName,
        "organization" : req.body.organization,
        "email": req.body.email,
        "mobile" : req.body.mobile,
    };

    console.log(data);

    **res.render('success.html',{email:data.email,password:data.password});**

});


//make sure that Service Workers are supported.
if (navigator.serviceWorker) {
    navigator.serviceWorker.register('service-worker.js', {scope: '/'})
        .then(function (registration) {
            console.log(registration);
        })
        .catch(function (e) {
            console.error(e);
        })
} else {
    console.log('Service Worker is not supported in this browser.');
}


// TODO add service worker code here
if ('serviceWorker' in navigator) {
    navigator.serviceWorker
        .register('service-worker.js')
        .then(function() { console.log('Service Worker Registered'); });
}

var server = app.listen(63342, function () {

    var host = server.address().host;
    var port = server.address().port;

    console.log("Example app listening at http://localhost:%s", port)
});

Here in the login section, If the email and password matches in the database then the site is directed to dashbaord.html otherwise we will show page-error.html using res.redirect() method. Also you can use res.render() to render a page in node.js

Codemaker2015
  • 12,190
  • 6
  • 97
  • 81