Why is the function app.get('/') not triggering? The problem seems to be related to cookies and user authentication

Need help with app.get('/') not being called

I am working on implementing cookies to allow multiple users to be logged in simultaneously. Currently, users can log in successfully. However, upon refreshing the page, all users get logged in as the same user (the last one who logged in). I suspect that this issue is related to app.get('/') not being triggered.

Below is the code I have. It's a bit lengthy, and I'm not sure which parts may impact the functionality of the app.get function.

let mysql = require("mysql2");

// Including express in our project
const express = require("express");
const sessions = require("express-session");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const { SourceMap } = require("module");
const { errorMonitor } = require("events");
const { receiveMessageOnPort } = require("worker_threads");
const bcrypt = require("bcrypt");
const { match } = require("assert");
const path = require("path")

// Creating an instance of our application by calling the express function
const app = express();

// Adding HTTP and calling its server function while passing our express app
const http = require("http").Server(app);
// Adding IO, passing socket.io reference and referencing http
const io = require("socket.io")(http);

app.use(express.json());
app.use(express.urlencoded({extended: true}));

app.use(cookieParser());

const oneDay = 1000 * 60 * 60 * 24;

app.use(sessions({
    secret: "secret key",
    saveUninitialized: true,
    cookie: { maxage: oneDay },
    resave: false,
}))

// Concentrating data for easy reading. If you're curious 
// about what extended does, visit body-parser on npmjs.com
// and scroll down to the extended section.
app.use(bodyParser.urlencoded({extended: false}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

let connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "MyPassword",
    database: "slutprojekt",
});

var session;

const dirname = './webbsidan'

console.log(__dirname)

// Setting the destination when someone 
// visits our web server. In this case,
// the person will land in a folder named
// 'webbsidan' where I'll place html documents,
// css, images, etc.
app.use(express.static(path.join(__dirname, '/webbsidan')))

app.get('/', (req, res) => {
    console.log('get /')
    // console.log(req)
    session = req.session;
    
    var Referer = "";
    
    if (req.rawHeaders.indexOf('Referer') != -1){
        
        Referer = req.rawHeaders[req.rawHeaders.indexOf('Referer')+1].split('/')
        Referer = Referer[Referer.length-1]
    }

    console.log(Referer)

    if (Referer != 'login.html' && !session.user){
        res.sendFile('/webbsidan/login.html', {root: __dirname})
    } else if (Referer == 'login.html' && session.user){
        res.sendFile('/webbsidan/index.html', {root: __dirname})
    }
})

app.post('/login', (req, res) => {
    console.log('login-post received');    

    let sql ="SELECT * FROM användare"

    connection.query(sql, function (err, result, fields) {
        if (err) throw err;
        let loggedIn = false

        for (const object of result){
            if (object.AnvändarNamn == req.body.username){
                
                if (bcrypt.compareSync(req.body.password, object.Lösenord)){
                    
                    loggedIn = true;
                    
                    session=req.session;
                    session.user=req.body.username;
                    session.userid=object.AnvändarID;
                    session.sid=req.rawHeaders[req.rawHeaders.indexOf('Cookie')+1]
                    // console.log(req.session)
                    
                    res.redirect('/');
                }
                else {
                    // console.log("incorrect password")
                }
                break;
            }
            else {
                // console.log('username incorrect:', object.AnvändarNamn);
            }
        }
        if (loggedIn == false){
            res.send('<script>alert("Login failed, try again"); window.location.replace("login.html")</script>')
        }
    })
})
...

// Instead of app.listen, we now run http.listen
http.listen(3000, () => {
    console.log("Server is running, visit http://localhost:3000");
});

function genDates(start, end){
    var getDaysArray = function(start, end) {
        for(var arr=[],dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
            arr.push(new Date(dt));
        }
        return arr;
    };

    var newStart = start.toISOString().replace("00:00:00", "10:10:10") // specify time so that no date is skipped or repeated when 
    var newEnd = end.toISOString().replace("00:00:00", "10:10:10") // time is shifted in march and october
    
    var daylist = getDaysArray(newStart, newEnd);

    var datelist= []

    daylist.forEach(element => {
        datelist.push(element.toISOString().split("T")[0])
    })

    var dowNameList = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

    let sql1 = `SELECT dateID, fullDate FROM kalender`
    connection.query(sql1, function (err, result, fields) {
        if (err) throw err;
        
        for (let i = 0; i < daylist.length; i++){
            
            var dowName = daylist[i].toString().split(" ")[0]
            var dowNum = dowNameList.indexOf(dowName)
            
            dowNum += 1
            
            const found = result.some(el => el.fullDate == datelist[i]) // Check if date already exists in database
            
            if (!found){
                let sql2 = `INSERT INTO kalender (dateID, fullDate, dowName, dowNum) VALUES (${i+1}, '${datelist[i]}', '${dowName}', ${dowNum});`
                connection.query(sql2, function (err, result, fields) {
                    if (err) throw err;
                })
            }
        }
    })
}

genDates(new Date("2023-01-01"),new Date("2023-12-31"));

Answer №1

Make sure you are properly handling the end of the request in get(/). If both conditions below are false

if (Referer != 'login.html' && !session.user){
    res.sendFile('/webbsidan/login.html', {root: __dirname})
} else if (Referer == 'login.html' && session.user){
    res.sendFile('/webbsidan/index.html', {root: __dirname})
}

you need to ensure the connection is properly terminated. Consider adding a default response at the end of get()

app.get('/', (req, res) => {
... codes

res.send()
}

Alternatively, you can change the else if to else

if (Referer != 'login.html' && !session.user){
        res.sendFile('/webbsidan/login.html', {root: __dirname})
    } else {
        res.sendFile('/webbsidan/index.html', {root: __dirname})
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to redirect users to the login page when they are logged out from a different tab or window?

Ensuring user authentication and managing inactivity are crucial components of my Nodejs application, where I leverage cookie-session and passport.js. app.use(require("cookie-session")({ secret:keys.session.secret, resave:false, saveUninitiali ...

Steps for transitioning a VUE JS project to TypeScript

Is it possible to transition a VUE JS project from JavaScript to TypeScript without rewriting everything? I heard from a friend that it can be done through the VUE CLI, but I haven't been able to find any documentation or articles on this method. Has ...

React useState Error: Exceeded maximum re-renders. React enforces a limit on the number of renders to avoid getting stuck in an endless loop

Can someone help me troubleshoot the 'Too many re-renders' error I'm encountering? I've implemented the try, catch method along with React hooks like useState and setState. My goal is to fetch data from an API and display it on a ...

Error: Trying to call an undefined function

Having trouble with an error on this line: $("#register-form").validate. Can anyone offer assistance? Furthermore, if I write this script, how should I incorporate it into the form? Will it function without being called? <script type="text/javascript ...

Element remains hidden until the developer console is activated

On my website, I've noticed that certain LayerSlider elements are remaining invisible until: The window is resized I disable the Bookmarks bar in Chrome (quite strange, right?) I switch on the Chrome debugger tools This issue is not exclusive to Ch ...

Executing JavaScript Code Through Links Created Dynamically

I am currently developing a website with a blog-style layout that retrieves information from a database to generate each post dynamically. After all posts are created, the header of each post will trigger an overlaid div displaying the full article for tha ...

How to ensure folder creation before uploading in Express.js

Is there a way to ensure the creation of a folder before uploading an image to prevent getting an ENOENT error? Here is the code I have been using: module.exports = function(router){ router.post('/result', directory.tmp, uploader.single, f ...

How can one identify a concealed glitch that exclusively occurs for a particular individual or hardware in a React environment?

Is it possible to identify a bug that occurs only with a particular individual or hardware in a React application? This bug is invisible and never appears during tests, but only manifests with a specific client within my company. Do you have any tips on h ...

Adding Pictures to Express/Multer API using Aurelia

Trying to integrate an Image/File-Upload feature into my Aurelia application. The Express API is functioning properly and is able to receive Files and Images using the Multer Plugin, as confirmed by testing with Postman. However, I am currently facing an ...

What is the process for creating a modal transition?

I am attempting to add animation to a modal using a transition effect. My goal is to open it slowly, either from the center of the screen or from the bottom. However, I am struggling to understand how this can be achieved... While searching on Google, I c ...

Encountered a syntax hiccup in my PHP and JavaScript codes

Below is my PHP code snippet: echo ("<td><img src='edit.jpg' width='20' alt='Edit' title='EDIT DATA' onClick=\"swipe2('" + . mysql_result($result, $i, 'no'). + '');'style= ...

Multiplying array elements within the Vuex state with the assistance of Socket.io

I have developed an application using Vue and Vuex that connects to a Node/Express backend with Socket.IO to instantly push data from the server to the client when necessary. The data sent to the clients is in the form of objects, which are then stored in ...

Utilizing the indexOf Method in AngularJS

Here is my array: emp=["111","56"]. This is the code I have: <input type="text" placeholder="Enter" class="form-control" name="Emp" ng-model="myModel.Emp" ng-required="currentStep ==2"/> <input type="text" placeholder="Enter" class="form-contro ...

Express failing to deliver static content

I am currently facing an issue while trying to host a vue.js single page app using a node.js server. The problem seems to be related to some express middleware. Specifically, my struggle lies in serving two components - my index.html file and a dist folde ...

Utilizing jQuery AJAX to enable a functional back button feature upon modifying HTML

While there are numerous inquiries regarding jQuery and Back button issues, the focal point is typically on maintaining history features when using the browser back/forward buttons. One specific query I have is how to load an AJAX-affected HTML page when ...

Removing items dynamically from a list created using ng-repeat

I have an array of nested JSON objects and I am using ng-repeat to create a list with the nested arrays. My goal is to dynamically delete items from this list upon button click by calling a function in the controller: $scope.remove= function(path){ va ...

Share a status on Facebook with an earlier date

How to Modify Facebook Post Date using Graph API facebook facebook-graph-api I am able to publish on my wall using the Graph API. By utilizing FB nod and graph, I now need to post on Facebook with a date from the past Afterwards, I can adjust the date man ...

Dynamically Loading CSS files in a JQuery plugin using a Conditional Test

I'm trying to figure out the optimal way to dynamically load certain files based on specific conditions. Currently, I am loading three CSS files and two javascript files like this: <link href="core.min.css" rel="stylesheet" type="text/css"> & ...

leaflet.js - Place a marker when clicked and update its position while dragging

Currently working on a small project that requires the ability to place a marker on an image-map powered by leaflet.js, and update its position if it's dragged. I was using the code below for this functionality but keep getting an error 'marker n ...

Encountering build:web failure within npm script due to TypeScript

Our project is utilizing the expo-cli as a local dependency in order to execute build:web from an npm script without requiring the global installation of expo-cli. However, when we run npm run build:web, we encounter the following exception. To isolate th ...