Categories: Node JSReact JS

Login Registration Form Using Node js React

In this video tutorials explains how to make the user login and Registration Form using Node js React, Express js,MongoDB.using MVC architecture. we have created routes,studentControler,studentServices,studentModel.

First you have to Create the Project

First Step Create the page which is server.js which use to connect the port and databases.

server.js

const express = require('express')
const app = express()
const mongoose = require('mongoose');
mongoose.set('strictQuery', false);
var routes = require('./route/routes');
const cors = require('cors');

app.use(cors(
  {
    origin: "http://localhost:3000"
  }

));

app.listen(9992,function check(err)
{
    if(err)
    console.log("error")
    else
    console.log("started")
});

mongoose.connect("mongodb://localhost:27017/gbs",{useNewUrlParser: true,  useUnifiedTopology: true },
function checkDb(error)
{
    if(error)
    {
        console.log("Error Connecting to DB");
    }
    else
    {
        console.log("successfully Connected to DB");
    }
});
app.use(express.json());
app.use(routes);

After that create the new Folder routes inside  the folder create file routes.js.

routes.js

var express = require('express');

var studentController = require('../src/student/studentController');
const router = express.Router();

router.route('/student/login').post(studentController.loginUserControllerFn);
router.route('/student/create').post(studentController.createStudentControllerFn);


module.exports = router;

after that create folder src inside the src create the newfolder user inside the folder make studentControler.js,studentServices.js,studentModel.js these files.

studentControler.js

var studentService = require('./studentService');

var createStudentControllerFn = async (req, res) => 
{
    try
    {
    console.log(req.body);
    var status = await studentService.createStudentDBService(req.body);
    console.log(status);

    if (status) {
        res.send({ "status": true, "message": "Student created successfully" });
    } else {
        res.send({ "status": false, "message": "Error creating user" });
    }
}
catch(err)
{
    console.log(err);
}
}

var loginUserControllerFn = async (req, res) => {
    var result = null;
    try {
        result = await studentService.loginuserDBService(req.body);
        if (result.status) {
            res.send({ "status": true, "message": result.msg });
        } else {
            res.send({ "status": false, "message": result.msg });
        }

    } catch (error) {
        console.log(error);
        res.send({ "status": false, "message": error.msg });
    }
}

module.exports = { createStudentControllerFn,loginUserControllerFn };

studentServices.js

var studentModel = require('./studentModel');
var key = '123456789trytryrtyr';
var encryptor = require('simple-encryptor')(key);

module.exports.createStudentDBService = (studentDetails) => {


   return new Promise(function myFn(resolve, reject) {

       var studentModelData = new studentModel();

       studentModelData.firstname = studentDetails.firstname;
       studentModelData.lastname = studentDetails.lastname;
       studentModelData.email = studentDetails.email;
       studentModelData.password = studentDetails.password;
       var encrypted = encryptor.encrypt(studentDetails.password);
       studentModelData.password = encrypted;

       studentModelData.save(function resultHandle(error, result) {

           if (error) {
               reject(false);
           } else {
               resolve(true);
           }
       });

   });

}

module.exports.loginuserDBService = (studentDetails)=> 
{
   return new Promise(function myFn(resolve, reject) 
   {
      studentModel.findOne({ email: studentDetails.email},function getresult(errorvalue, result)
      {
         if(errorvalue)
         {
            reject({status: false, msg: "Invaild Data"});
         }
         else
         {
            if(result !=undefined &&  result !=null)
            {
               var decrypted = encryptor.decrypt(result.password);

               if(decrypted== studentDetails.password)
               {
                  resolve({status: true,msg: "Student Validated Successfully"});
               }
               else
               {
                  reject({status: false,msg: "Student Validated failed"});
               }
            }
            else
            {
               reject({status: false,msg: "Student Error Detailssss"});
            }

         }
      
      });
      
   });
}

studentModel.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var studentSchema = new Schema({

    firstname: {
        type: String,
        required: true
    },
    lastname: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }

});

module.exports = mongoose.model('student', studentSchema);

React

React is a front-end application we have already created the folder front end inside the folder open the command prompt and type the commands.

Installing React

npx create-react-app front-end

After that you need to install the required dependencies

  1. npm i axios

For managing the Api requests

2.npm i react-router-dom

For managing the routes

After that go to the bootstrap webite and copy the bootstap css style and paste inside the

index.html  inside the head tag.

After install open the project into Vscode Editor.create the folder inside src which name is components inside the folder create 3 files. Home.jsx,Register.jsx,Login.jsx

Register.jsx

import axios from "axios";
import {  useState } from "react";


function Register() {

    const [fname, setFName] = useState("");
    const [lname, setLName] = useState("");

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");


    async function save(event) {
        event.preventDefault();
        try {
          await axios.post("http://localhost:9992/student/create", {
          firstname: fname,
          lastname: lname,
          email: email,
          password: password,
          });
          alert("Student Registation Successfully");

        } catch (err) {
          alert(err);
        }
      }

    return (
     <div>
        <div class="container mt-4" >
    <div class="card">
            <h1>Student Registation</h1>
    
    <form>
        <div class="form-group">
          <label>First name</label>
          <input type="text"  class="form-control" id="fname" placeholder="Enter Name"
          
          value={fname}
          onChange={(event) => {
            setFName(event.target.value);
          }}
          />

          
        </div>

        <div class="form-group">
            <label>Last name</label>
            <input type="text"  class="form-control" id="lname" placeholder="Enter Name"
            
            value={lname}
            onChange={(event) => {
              setLName(event.target.value);
            }}
            
            />
          </div>
    
        <div class="form-group">
          <label>email</label>
          <input type="email"  class="form-control" id="email" placeholder="Enter Name"
          
          value={email}
          onChange={(event) => {
            setEmail(event.target.value);
          }}
          
          />
          
          
          
        </div>

        <div class="form-group">
            <label>password</label>
            <input type="password"  class="form-control" id="password" placeholder="Enter Fee"
            
            value={password}
            onChange={(event) => {
              setPassword(event.target.value);
            }}
            
            />
          </div>


    
        <button type="submit" class="btn btn-primary mt-4" onClick={save} >Save</button>
       
      </form>
    </div>




    </div>



     </div>
    );
  }
  
  export default  Register;

Login.jsx

import axios from "axios";
import {  useState } from "react";
import { useNavigate } from 'react-router-dom';


function Login() {

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const navigate = useNavigate();


    async function login(event) {
        event.preventDefault();
        try {
          await axios.post("http://localhost:9992/student/login", {
            email: email,
            password: password,
            }).then((res) => 
            {
             console.log(res)
             const data = res.data;
             
             if (data.status === true) 
             {
                alert("Login Successfully"); 
                navigate('/home');
             } 
             else 
             {
                   alert("Login Failed")
             }  
          }, fail => {
           console.error(fail); // Error!
  });
        }

 
         catch (err) {
          alert(err);
        }
      
      }
      


    return (
     <div>
            <div class="container">
            <div class="row">
                <h2>Login</h2>
             <hr/>
             </div>

             <div class="row">
             <div class="col-sm-6">
 
             <form>
             <div class="form-group">
          <label>email</label>
          <input type="email"  class="form-control" id="email" placeholder="Enter Name"
          
          value={email}
          onChange={(event) => {
            setEmail(event.target.value);
          }}
          
          />
          
          
          
        </div>

        <div class="form-group">
            <label>password</label>
            <input type="password"  class="form-control" id="password" placeholder="Enter Fee"
            
            value={password}
            onChange={(event) => {
              setPassword(event.target.value);
            }}
            
            />
          </div>
                  <button type="submit" class="btn btn-primary" onClick={login} >Login</button>
              </form>

            </div>
            </div>
            </div>

     </div>
    );


  }
  
  export default Login;

Home.jsx

function Home() {
    return (
     <div>
        <h1>index</h1>
     </div>
    );
  }
  
  export default Home;

Configure the Routes

open the App.js

App.js

import { BrowserRouter,Routes,Route } from "react-router-dom";

import UserRegistation from "./components/UserRegistation";
import Login from "./components/Login";

import Home from "./components/Home";

function App() {
  return (
   <div>
        <BrowserRouter>
            <Routes>
              <Route path="/home" element= { <Home/>} />
              <Route path="/register" element= { <UserRegistation/>} />
              <Route path="/" element= { <Login/>} />
            </Routes>
        </BrowserRouter>
   </div>
  );
}

export default App;

i have attached the video link below. which will do this tutorials step by step.

 

admin

Recent Posts

Employee Working Hours Calculation System using C#.net

Initialize the employee number, Hourswork,and Hoursrate to calculate a grosswage use the following condition. if…

1 week ago

Java Payroll System Calculate Employee Overtime

Act as a Java developer to create a program that calculates the gross wage for…

1 week ago

Employee Working Hours Calculation System using Java

Initialize the employee number, Hourswork,and Hoursrate to calculate a grosswage use the following condition. if…

2 weeks ago

Laravel 11 School Management System

In this tutorial, we will teach you how to create a simple school management system…

2 weeks ago

How to Make Admin Panel Using React MUI

I have design the Admin Basic templete using React MUI Design Admin Dashboard and Login.Here…

4 weeks ago

Install Laravel Breeze for Authentication Using Laravel 11

In this tutorial ,i am to going teach the Laravel Breeze.Laravel Breeze provides a simple…

1 month ago