What causes the slow loading of my login page when I attempt to log in?

Need assistance with my login route. When I click on the login button, the page loads slowly and returns an error instead of redirecting to the desired page or rendering it when I'm logged in. For privacy reasons, some code has been removed. Feel free to use your own database for testing purposes. Any help would be greatly appreciated. By the way, I have updated the code to test a different approach.

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const { nextTick } = require('process');

const app = express();

app.use(bodyParser.urlencoded({extended: false}));

// mongoose.connect('mongodb+srv://apiuser:[email protected]/users?retryWrites=true&w=majority');

// const userSchema = new mongoose.Schema({
//     email: String,
//     password: String
// });

let objUser = {
    username: 'aiman',
    password: '123'
}


// const User = new mongoose.model("User", userSchema);

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

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

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

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

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

app.post('/login', function(req,res, err){
    let username = req.body.username;
    let password = req.body.password;

    for(let i = 0; i < objUser.length; i++){
        if(objUser[i].username == username && objUser[i].password == password){
            res.redirect('/');
        } else{
            console.log(err);
        }
    }
});

app.listen(3001, function(req,res){
    console.log("Server started on port 3001");
});

Answer â„–1

The issue at hand is that when the client is awaiting a response, if an error occurs on the server side, no response is sent back to inform them of what went wrong. Responses are only sent to the client in cases where everything goes smoothly.

As a result, the client ends up waiting indefinitely until they receive an error message like "maximum execution time exceeded," without any prior notification.

app.post('/login', function(req,res){
    const email = req.body.email
    const password = req.body.password

   User.findOne({email: email}, function(err, foundUser){
       if(err){
           console.log(err);
           res.status(500).json({ message: "Something went wrong" })
       } else{
           if(foundUser){
               if(foundUser.password === password){
                   res.redirect('/repayment');
               }else {
                  //password not equal
                  res.status(400).json({ message: "Passwords do not match" });
               }
           }else {
              //user not found 
              res.status(404).json({ message: "User not found" })
           }
       }
   }); 
});

It is imperative to send a response in case something deviates from the expected outcome, including for your /register route.

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

Angular 5 with Typescript encountered a failure in webpack due to the absence of the property "data" on the Response

I am encountering an issue during webpack compilation. It compiles successfully if I remove .data, but then the page crashes with calls from template->component (which in turn calls a service). Here is the error I am facing: ERROR in src/app/compone ...

Troubleshooting Problems with POST Requests in ExpressJS

Currently, I am working on developing a feature in NodeJS that allows users to upload files. However, I am encountering difficulties while attempting to make a simple POST request. In my index.ejs file, I have written code that generates a form and initia ...

My function is not working with jQuery's .append method

As a newcomer to javascript and jquery, I am experimenting with adding html through a javascript function. In an attempt to place the contents of variable "y" at a specific location, I am using a div tag with the id of "Contacts" and trying to append elem ...

Combine Woocommerce Product Bundles with Ajax Cart additions and the ability to continue shopping after adding items to your cart

I am currently working on implementing the functionality to add WooCommerce product bundles to my cart using ajax. Once the products are successfully added, I want two buttons to be displayed - one for viewing the cart and the other for continuing shopping ...

Should I generate an array or pull data directly from the database?

Hey there, I've got this JavaScript app and could really use some input or tips. Here's the idea: Users log in to try and defeat a 'boss', with each player working together in the game. Let's say the 'boss' has 10 millio ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...

Floating elements changing positions as the user scrolls

Have you ever wondered how websites like Facebook manage to float certain elements, such as a menu bar or social plugin, when the user scrolls past a specific point? This functionality can be achieved through JavaScript (jQuery) events that trigger when a ...

Utilizing JavaScript to create multiple HTML tables from JSON data

Is it necessary to create separate tables in HTML for each set of JSON data when all tables have the same number of columns (2 columns)? I am looking to minimize the JavaScript function that displays the table with the current JSON data. Can I use one tabl ...

Establish a connection between an already existing PostgreSQL database and an Express.js application by utilizing

Looking to integrate my PostgreSQL database into my express js project using sequelize. Any advice on how to proceed? ...

Clicking on the element will not cause the body to scroll

For some reason, I need to keep the onclick function, but I'm struggling to make it work as intended. What I want is for the body to slide to the next logo when the previous logo is clicked. This is a simplified version of what I have: <div class ...

Having trouble drawing over buttons in HTML5 Canvas?

window.addEventListener("load", () => { const canvas = document.querySelector("#canvas"); const ctx = canvas.getContext("2d"); const color = document.querySelector("#color"); const strokeWeight = document.querySelector("#strokeWeight"); ...

Ways to halt streaming without shutting down the Node.js server

I am currently facing an issue with closing a Twitter stream, as it causes my server to crash and requires a restart. Is there a way to close the stream without affecting the Nodejs (express) server? Here is the error message I am encountering: file:///mnt ...

Utilize Google Console with Chrome and jQuery to extract the name and URL from HTML content

I am trying to parse the HTML source code in order to extract all links and text from it, and then store this information in a multidimensional array, all within the Google Chrome console. Here's a snippet of the code that needs to be repeated 10 tim ...

Displaying images using <img src='path' /> in React is causing some troubles

I'm currently working on a React template for the front page and I need to display various local dummy images. Within my <Main /> component, I import other components that pass the image path as a parameter, like this: <Container type ...

Recreating a <select> element and verifying it once more using JS/HTML5

Before I delve into my issue, I would like to offer an apology for any errors in my English. So, the HTML code I am working with looks like this: <body> <div id="container"> <div id="taskList"> <div id="firstTask"> & ...

How can I use Grid List and Icon Button in Material UI as individual buttons with onClick functionality?

I've been experimenting with the grid list feature from the Material UI framework, found here: https://material-ui.com/components/grid-list/#grid-list-with-titlebars My current challenge involves adding onClick actions to both the GridListTile compon ...

The HTML code may fade away, but the JavaScript is still up and running behind the

Switching between different div elements in my HTML document is a challenge. Here's the code I currently have: <div id="screen1" class="current"> <div id="press_any_key_to_continue"> <font style="font-family: verdana" color="yellow ...

HTTPS is causing issues with the functionality of the API route

I currently have a node server running on port 3000 specifically to handle api requests. Everything seems to be functioning fine as expected... However, when I try accessing this, it doesn't seem to work. Could someone possibly shed some light on w ...

Tips on declaring an object with a nested array of objects in TypeScript

In my code, I have defined two classes. One is called Stuff and the other is called Thing. class Stuff { constructor() { } things: Thing[] = []; name: string; } class Thing { constructor() { } active: boolean; } As I was working on my applicat ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...