Home Angular Login Registration Using Node js Angular

Login Registration Using Node js Angular

14 min read
0
0
7,023

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

First you have to Create the Project

npm init

After run the command package.json file has been created.

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:4200"
  }

));

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);

 

Angular

Angular 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 Angular CLI

npm install -g @angular/cli

After that create the new Project of Angular running by the following command

ng new frond-end

After complete the installation then run the project using following command.

ng serve

it will generate the url link to run the angular application.paste the url in to the browser

Now you see the Angular Welcome Page.

After that open the Angular project into VS code editor.

now you can see the following file structure

then you have create the following components by typing the command

ng g c login
ng g c register 
ng g c home

After components has been created you have to visit the bootstrap site and copy the css
file and paste inside the index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>FrondEnd</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>

After that add module inside app.module.ts
inside the imports section add the FormsModule and HttpClientModule

if the path is not get automatically copy and paste it

import { HttpClientModule } from ‘@angular/common/http’;
imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ]

 

register.component.html

<div class="container mt-4" >
    <div class="card">
            <h1>Student Registation</h1>
    
    <form>
        <div class="form-group">
          <label>First name</label>
          <input type="text" [(ngModel)]="firstname" [ngModelOptions]="{standalone: true}" class="form-control" id="stname" placeholder="Enter Name">
        </div>

        <div class="form-group">
            <label>Last name</label>
            <input type="text" [(ngModel)]="lastname" [ngModelOptions]="{standalone: true}" class="form-control" id="stname" placeholder="Enter Name">
          </div>
    
        <div class="form-group">
          <label>email</label>
          <input type="email" [(ngModel)]="email" [ngModelOptions]="{standalone: true}" class="form-control" id="course" placeholder="Enter Name">
        </div>

        <div class="form-group">
            <label>password</label>
            <input type="password" [(ngModel)]="password" [ngModelOptions]="{standalone: true}" class="form-control" id="fee" placeholder="Enter Fee">
          </div>

        <button type="submit" class="btn btn-primary mt-4" (click)="save()" >Save</button>
       
      </form>
    </div>

register.component.ts

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent {

  firstname: string ="";
  lastname: string ="";
  email: string ="";
  password: string ="";

  constructor(private http: HttpClient) 
  {
  }

  ngOnInit(): void
  {
  }

  register()
  {
    let bodyData = 
    {
      "firstname" : this.firstname,
      "lastname" : this.lastname,
      "email" : this.email,
      "password" : this.password,
    };
    this.http.post("http://localhost:9992/student/create",bodyData).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Registered Successfully")
    });
  }

  save()
  {
    this.register();
  }

}

 

login.component.html

<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 for="exampleInputEmail1">Email address</label>
                    <input type="text" [(ngModel)]="email" [ngModelOptions]="{standalone: true}" class="form-control" id="stname" placeholder="Enter Email"/>
                  </div>
                  <div class="form-group">
                    <label for="exampleInputPassword1">Password</label>
                    <input type="password" [(ngModel)]="password" [ngModelOptions]="{standalone: true}" class="form-control" id="stname" placeholder="Enter Password"/>
                  </div>
                <br>
                  <div class="form-group">
                    <button type="submit" class="btn btn-primary" (click)="login()">Login</button>
                  </div>
       
                </form>
           </div>
      </div>
  </div>

login.component.ts

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {

  email: string = '';
  password: string = '';

  isLogin: boolean = true;
  erroMessage: string = "";

  constructor(private router: Router,private http: HttpClient) {}

  login() {
    console.log(this.email);
    console.log(this.password);

    let bodyData = {
      email: this.email,
      password: this.password,
    };

        this.http.post("http://localhost:9992/student/login", bodyData).subscribe(  (resultData: any) => {
        console.log(resultData);

        if (resultData.status) 
        {
      
           this.router.navigateByUrl('/home');
    

        } 
        else
         {
          alert("Incorrect Email or Password");
          console.log("Errror login");
        }
      });
    }

}

app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: LoginComponent
  },
  
  {
  path: 'home',
  component: HomeComponent,
  
  },
  {

  path: 'register',
  component: RegisterComponent,
  }
];

 

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

Load More Related Articles
Load More By admin
Load More In Angular

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Employee Working Hours Calculation System using Java

Initialize the employee number, Hourswork,and Hoursrate to calculate a grosswage use the f…