Node.js – Redirect on another html page

expressnode.js

I'm new to NodeJS and express, and here is what I want to do :

After checking the connexion values, I want to redirect my user on his main page. I don't want to change the URL, but just show another html page.

Here is the code, and where I want to put the redirection :

var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);

server = server.listen(8080);

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/public/login.html');
});

app.use(express.static(path.join(__dirname, '/public')));

io.on('connection', function (socket) {

 socket.on('connexion_client', function(data) {
  if(input_are_ok) {
  // When the client is connected & his input are checked

  // HERE: I want to redirect to 'public/index.html'

  }
 }); // socket.on
}); // io.on

Thanks.

Best Answer

You can use res.redirect([status,] path) like this:

if (input_are_ok) {
    res.redirect('public/index.html');
}

This will redirect to the given URL using the specified HTTP status code status. If no status code is specified, the status code defaults to 302 (which is fine in most use cases). More information in the official documentation.

Related Topic