problem of the node server don't take my to next page ejs

33 Views Asked by At

in my code here i'am traying to check from the username and password if exist in DB or not ,
the problem is when i open the page and write username and password and click on login the page just refresh and don't take me to next page, but when i'am doing this from insomnia ( app like postman ) and end the username and password as json it's work and take me to next page

the code in server :

const ejs = require("ejs");
const exprees = require("express");
const bcrypt = require("bcrypt");
const mysql = require("mysql");
const { json } = require("body-parser");
const { restart } = require("nodemon");
const path = require('path');
const flash = require('express-flash');
const session = require('express-session');

//configrtaion app
const app = exprees();
app.use(exprees.json());
app.use(exprees.static(path.join(__dirname, 'public')));


//view engine ejs
app.set('view engine','ejs');

//end point for login page
app.get("/loginAdminPage",(req,res)=>{
  res.render("admin/login",{
    message: ''
  });
});

//this end point for login
app.post("/loginAdmin", async(req, res) => {
  try {
    let adminPassword = req.body.password;
    let adminUserName = req.body.userName;

    let admin = new Admin();
    
    //check if user namae and password is found
    const checkLogin = await admin.selectAdminFromDBForLogin(adminUserName,adminPassword);
    if(checkLogin===false){
      res.render("admin/login.ejs",{message:'اسم المستخدم او كلمة المرور خاطئة'});
      return false;
    }
    console.log(savedData[0].adminID);
    res.render("admin/mainPage.ejs",{
      ID:savedData[0].adminID,
      name:savedData[0].adminName,
      userName:savedData[0].adminUserName,
      gender:savedData[0].adminGender,
      validity:savedData[0].adminValidity,
    });
    

   

  } catch (err) {
    console.log(err);
    res.send(err);
  }
});

the html(ejs) code:

<!DOCTYPE html>
<html lang="en" dir="rtl">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>تسجيل دخول مستخدم النظام </title>
    <link rel="stylesheet"  href="../../bootstrap-5.0.2-dist/css/bootstrap.css"/>
  </head>
  <body style="background-color:  rgb(14, 9, 66);">
    <section class="vh-100 gradient-custom" style="background-color: rgb(14, 9, 66)">
      <div class="container py-5 h-100">
        <div class="row justify-content-center align-items-center h-100">
          <div class="col-12 col-lg-9 col-xl-7">
            <div class="card shadow-2-strong card-registration" style="border-radius: 15px">
              <div class="card-body p-4 p-md-5">
                <h3 class="mb-4 pb-2 pb-md-0 mb-md-5" style="color: red;"><%=message%></h3>
                <form>

                    <div class="col-md-12 mb-4">
                      <div class="form-outline">
                        <input type="text" id="userName" class="form-control form-control-lg userName" placeholder="أدخل اسم المستخدم"/>
                      </div>
                    </div> 

                    <div class="col-md-12 mb-4">
                      <div class="form-outline">
                        <input type="password" id="password" class="form-control form-control-lg password" placeholder="أدخل كلمة المرور"/>
                      </div>
                    </div>

                  <div class="mt-4 pt-3 row">
                   <input class="btn btn-lg login" type="submit" value="تسجيل" style="background-color: rgb(255, 136, 0)"/>
                  </div>

                  <div class="mt-4  row">
                    <input class="btn btn-lg forgetPassword" type="submit" value="نسيت كلمة المرور" style="background-color: rgb(255, 136, 0)"/>
                   </div>

                  <p class="text-center text_muted mt-5 mb-0">ليس لديك حساب؟<a href="/registerAdminPage" class="fw-bold text-body"><u>تسجيل مستخدم جديد</u></a></p>
                </form>

              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
    
    <script src="login.js"></script>
    <script src="../../sweetalret.js"></script>
    <script src="../../bootstrap-5.0.2-dist/js/popper.min.js"></script>
    <script src="../../bootstrap-5.0.2-dist/js/jquery-3.7.1.min.js"></script>
    <script src="../../bootstrap-5.0.2-dist/js/bootstrap.js"></script>
  </body>
</html>

the javascript of login page :


// get varible info from page
let userName = document.querySelector(".userName");
let password = document.querySelector(".password");


//get button for control
let button = document.querySelector(".login");

//function of check from value
function checkUserNameValue(userName) {
  try {
    // check the length of userName
    if (userName.length < 4 || userName.length > 10) {
      console.log("username !!! number of letter not in range");
      document.querySelector(".userName").style.borderColor="red";
      Swal.fire({
        icon: "error",
        title: "خطأ...",
        text: "طول احرف اسم المستخدم لا تقل عن 4 احرف ولا تزيد عن 10",
      });
      return false;
    }

    //for loop for check latters
    for (let i = 0; i < userName.length; i++) {
      let ascii = userName.charCodeAt([i]);

      //check if the firest is number
      if (i == 0 && ascii > 47 && ascii < 58) {
        console.log("wrong !!! username start with number or underscore (_) ");
        document.querySelector(".userName").style.borderColor="red";
        Swal.fire({
          icon: "error",
          title: "خطأ...",
          text: "يجب انا لايحتوي اسم المستخدم على رقم في البداية",
        });
        return false;
      }

      //check if has special charecters
      if ((ascii < 65 || ascii > 90) &&(ascii < 97 || ascii > 122) &&(ascii < 48 || ascii > 57) &&ascii != 95) {
        console.log("wrong !!! username have special charecter");
        document.querySelector(".userName").style.borderColor="red";
        Swal.fire({
          icon: "error",
          title: "خطأ...",
          text: "يجب ان يحتوي اسم المستخدم على احرف او ارقام فقط",
        });
        return false;
      }
    }
  } catch (err) {
    console.log(err);
    return false;
  }
}
function checkPasswordValue(password) {
  try {
    // check from length of password
    if (password.length < 8 || password.length > 15) {
      console.log("password !!! number of password not in range");
      document.querySelector(".password").style.borderColor="red";
      Swal.fire({
        icon: "error",
        title: "خطأ...",
        text: "يجب ان يكون طول احرف كلمة المرور لا تقل عن 8 ولا تزيد عن 15",
      });
      return false;
    }
  } catch (err) {
    console.log(err);
    return false;
  }
}

// change the border to input to red does not match the constrctor  
userName.addEventListener("change",()=>{
    document.querySelector(".userName").style.borderColor="darkgray";
    checkUserNameValue(userName.value);
})
password.addEventListener("change", ()=>{
    document.querySelector(".password").style.borderColor="darkgray";
    checkPasswordValue(password.value);
})

//send the data to server
button.addEventListener("click", (event) => {
  //event.preventDefault();
  let check = checkUserNameValue(userName.value);
  check = checkPasswordValue(password.value);

  if (check == false) {
    event.preventDefault();
    return false;
  }

  let obj = {
    userName: userName.value,
    password: password.value,
  }
  fetch("/loginAdmin", {
    method: "post",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(obj)
  })
})```

by the why the server resaved the username and password and check if exist or not , in the consle i wrote code to display login or not login , if username and password is correct it display login withe the id in DB and if wrong it display the error in user name or password 
1

There are 1 best solutions below

1
GreenSaiko On

I'm not sure if it will solve your problem, but I can see some issues.

First of all, if you use the fetchAPI to do the request on the login route, do not use <input type="submit"> as this will only cause problems, especially since you only call event.preventDefault(); if the inputs are not acceptable. So if someone enters accepted inputs, it will load the current page because there is no action="{LINK}" attribute on neither the <form>, nor the <input type=submit> element, so automatically sets the action to "" (check this question). I'm not sure if the fetch request still fires after the page has been submited/refreshed, but it's chaos anyway since it tries to submit and fetch.

It is recommended to use the <button> tag instead of <input type="submit"> because it provides a lot more functionality to the button element (check this answer). And if you need or want to stick with the <input> button, use <input type="button">, so it doesn't automatically submit when clicked, this also removes the necessity of event.preventDefault();.

I hope for you that this will solve your problem.

Furthermore, you might want to check out Regular expressions. For example in your checkUserNameValue method, to check all the things at once you could say /^[^0-9_][a-zA-Z]{3,9}$/.test(userName) and then act accordingly if false or true. This is obviously not what you want, since you want to have different error messages depending on the issue, so you could use it like for example /^[^0-9_]{1}/.test(userName) to just test if it start with a number or underscore.