Node JS

Nodejs Angular with Mysql Crud Application

This tutorial will teach you how to make Crud Application using Node JS with Angular Frontend application with Mysql  Database using Api access Crudapplication.

Create the Node Js Project Type on type command prompt

npm init

and press enter key.after that you have the fill configation of project.after done stuff you
will get the package.json file.

after that you have to install the following dependencies

Express
body-parser
Mysql

you have to create the database and tables in mysql database.

After done the stuff you have to create the file server.js

Server.js

const express = require('express')
const bodyParser = require('body-parser')
const mysql = require("mysql");
const server = express();
server.use(bodyParser.json());


//Establish the database connection

const db = mysql.createConnection({

    host: "localhost",
    user: "root",
    password: "",
    database: "dbsmschool",

});

db.connect(function (error) {
    if (error) {
      console.log("Error Connecting to DB");
    } else {
      console.log("successfully Connected to DB");
    }
  });

//Establish the Port

  server.listen(8085,function check(error) {
    if (error) 
    {
    console.log("Error....dddd!!!!");
    }

    else 
    {
        console.log("Started....!!!! 8085");

    }
});

//Create the Records

server.post("/api/student/add", (req, res) => {
    let details = {
      stname: req.body.stname,
      course: req.body.course,
      fee: req.body.fee,
    };
    let sql = "INSERT INTO student SET ?";
    db.query(sql, details, (error) => {
      if (error) {
        res.send({ status: false, message: "Student created Failed" });
      } else {
        res.send({ status: true, message: "Student created successfully" });
      }
    });
  });



//view the Records

server.get("/api/student", (req, res) => {
    var sql = "SELECT * FROM student";
    db.query(sql, function (error, result) {
      if (error) {
        console.log("Error Connecting to DB");
      } else {
        res.send({ status: true, data: result });
      }
    });
  });


//Search the Records

server.get("/api/student/:id", (req, res) => {
    var studentid = req.params.id;
    var sql = "SELECT * FROM student WHERE id=" + studentid;
    db.query(sql, function (error, result) {
      if (error) {
        console.log("Error Connecting to DB");
      } else {
        res.send({ status: true, data: result });
      }
    });
  });



//Update the Records

server.put("/api/student/update/:id", (req, res) => {
    let sql =
      "UPDATE student SET stname='" +
      req.body.stname +
      "', course='" +
      req.body.course +
      "',fee='" +
      req.body.fee +
      "'  WHERE id=" +
      req.params.id;
  
    let a = db.query(sql, (error, result) => {
      if (error) {
        res.send({ status: false, message: "Student Updated Failed" });
      } else {
        res.send({ status: true, message: "Student Updated successfully" });
      }
    });
  });



  //Delete the Records

  server.delete("/api/student/delete/:id", (req, res) => {
    let sql = "DELETE FROM student WHERE id=" + req.params.id + "";
    let query = db.query(sql, (error) => {
      if (error) {
        res.send({ status: false, message: "Student Deleted Failed" });
      } else {
        res.send({ status: true, message: "Student Deleted successfully" });
      }
    });
  });

 

Angular

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

Select the SCSS Style for the Advanced CSS and Press Enter Key.

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

ng serve

HttpClientModule

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomerComponent } from './customer/customer.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    CustomerComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule

  
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

add these module into the app.module.ts file  then only we will manage the forms and Http requests

studentCrud.compoent.html

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

        <div class="form-group">
            <label>Fee</label>
            <input type="text" [(ngModel)]="fee" [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>
    
  
    
        <div class="container mt-4" >
            <h1>Student Table</h1>
        <table class="table">
            <thead>
             <h1 *ngIf="!isResultLoaded">Loading.................</h1>      
            <tr>
                <th scope="col">ID</th>
                <th scope="col">Student Name</th>
                <th scope="col">Course</th>  
                <th scope="col">Fee</th>  
              </tr>
            </thead>
            <tbody>
                <tr *ngFor="let StudentItem of StudentArray">
                <td>{{StudentItem.id  }}</td>
                <td>{{StudentItem.stname }}</td>
                <td>{{StudentItem.course }}</td>
                <td>{{StudentItem.fee }}</td>
                <td>
                  <button type="button" class="btn btn-success" (click)="setUpdate(StudentItem)">Edit</button>
                  <button type="button" class="btn btn-danger" (click)="setDelete(StudentItem)">Delete</button>            
                </td>
              </tr>          
            </tbody>
          </table>
        </div>

studentCrud.compoent.ts

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

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

  StudentArray : any[] = [];
  isResultLoaded = false;
  isUpdateFormActive = false;

  stname: string ="";
  course: string ="";
  fee: string ="";
  currentStudentID = "";

  constructor(private http: HttpClient ) 
  {
    this.getAllStudent();
  }

  ngOnInit(): void {
  }

  getAllStudent()
  { 
    this.http.get("http://localhost:9002/api/student/")
    .subscribe((resultData: any)=>
    {
        this.isResultLoaded = true;
        console.log(resultData.data);
        this.StudentArray = resultData.data;
    });
  }


  


  register()
  {
   // this.isLogin = false; 
   // alert("hi");
    let bodyData = {
      "stname" : this.stname,
      "course" : this.course,
      "fee" : this.fee,
    };

    this.http.post("http://localhost:9002/api/student/add",bodyData).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Registered Successfully")
        this.getAllStudent();
      //  this.name = '';
      //  this.address = '';
      //  this.mobile  = 0;
    });
  }

  setUpdate(data: any) 
  {
   this.stname = data.stname;
   this.course = data.course;
   this.fee = data.fee;
  

   this.currentStudentID = data.id;
 
  }

  UpdateRecords()
  {
    let bodyData = 
    {
      "stname" : this.stname,
      "course" : this.course,
      "fee" : this.fee
    };
    
    this.http.put("http://localhost:9002/api/student/update"+ "/"+ this.currentStudentID,bodyData).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Registered Updateddd")
        this.getAllStudent();
      
    });
  }
 
  save()
  {
    if(this.currentStudentID == '')
    {
        this.register();
    }
      else
      {
       this.UpdateRecords();
      }       

  }


  setDelete(data: any)
  {
    this.http.delete("http://localhost:9002/api/student/delete"+ "/"+ data.id).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Deletedddd")
        this.getAllStudent();
    });
  }
}

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

admin

Recent Posts

How to Laravel cache clear

Laravel cache clear , you can use the Artisan command-line tool that comes with Laravel.…

10 minutes ago

Installing Vue.js in Laravel Project

Vue.js is a powerful JavaScript framework for creating dynamic user interfaces, while Laravel is a…

20 minutes ago

Do I Return in Void Function in Java?

In Java, a void function (or method) does not return any value. However, you can use the return statement…

10 hours ago

Is Java Hard to Learn?

Is Java Hard to Learn is it True? Java is one of the most popular…

11 hours ago

How to generate random with weight java

Generating Random Numbers with Weights in Java Random number generation with weighted probabilities is a…

11 hours ago

Building JSP AJAX CRUD Application

Introduction to JSP AJAX CRUD Applications Building web applications has become more dynamic with the…

2 days ago