dll dll - 2 months ago 11
Node.js Question

redirected to wrong html page when using express.static(__dirname) function in node.js with express

I have a login page called login.html and an index page called index.html. I want to make a authentication and that only a connected user can access the index page.

I did not implement the post method on the login HTML page. I have to manually send the login username and password by going on this url:

http://localhost:2222/?username=a&password=b


Everything worked but I could not see my css, js and some other files in the index.html. To solve this problem I added this at the beginning of my code:

app.use(express.static(__dirname));


The problem is that now if I go to the localhost:2222 it shows the index.html file instead of the login.html file. Even if I use:

app.get('/', function (req, res) {
res.redirect('/login');
});


How does it come ? How can I solve this ?

The full code is:

var express = require("express");
var port = process.env.PORT || 2222;
var app = express();
app.use(express.static(__dirname));
var session = require('express-session')
app.use(session({
secret: 'keyboardcat',
resave: true,
saveUninitialized: true
}));

function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.sendfile('login.html');
} else {
next();
}
}
app.get('/', function (req, res) {
res.redirect('/login');
});
app.get("/login", function(req, res) {
if (req.query.username === 'a' && req.query.password === 'b') {
req.session.user_id = req.query.username;
res.redirect('index');
} else {
res.sendfile('login.html');
}
});
app.get('/index', checkAuth, function(req, res){
res.sendfile('index.html');
});

app.get('/logout', function (req, res) {
delete req.session.user_id;
res.redirect('/login');
});


My file tree is as follow: index.html, login.html and server.js are in a folder called server. In this folder sever are also 4 folders: JS, CSS, Images and Random.

Answer

You are using project folder for static as you posted app.use(express.static(__dirname));. ExpressJS using index.html as default index page. So you need to rename index.html to something else like main.html and use res.sendfile('main.html');.

Alternate Solution:

Create a folder say public and put all static content(js, css and images) into public folder and please do not put html file into public folder and use app.use(express.static(__dirname) + '/public');.