Skip to main content

React-JS CRUD Operation using NODE JS API


In this example, I have described the complete process of creating API in Node JS and Consume into React JS Application.

I have created a complete GRID System under-react js application using Login, Registration, Select, Insert, Update, and Delete Record.

First Install NODE JS and React JS in Machine

Create NODE JS Environment and React JS Project into System.

Step first:-

Create a Folder and run npm init  command

Step2nd:-

Create API using NODE JS

before execution this code

run the following command

npm install express

npm install bodyparser

npm intsall cors

npm install mongodb

This code contains all APIs including Registration, Login, Create, Update, Find, Delete, and Select under Registration and Customer Table under the Mongo DB database.

Create File using API-Example.JS

const Express = require("express");

const BodyParser = require("body-parser");
var cors = require('cors')
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const CONNECTION_URL ="mongodb://localhost:27017/" ;
const DATABASE_NAME = "ecommerce";
var app = Express();
app.use(cors())
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
var database, collection;
app.listen(5000, () => {
    MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
        if(error) {
            throw error;
        }
        database = client.db(DATABASE_NAME);
        collection = database.collection("customer");
        collection1 = database.collection("reg");
        console.log("Connected to `" + DATABASE_NAME + "`!");
    });

});
app.post("/customer", (request, response) => {
    collection.insert(request.body, (error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        response.send(result.result);
    });
});
app.get("/customer", (request, response) => {
    collection.find({}).toArray((error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        response.send(result);
    });
});
app.get("/customer/:id", (request, response) => {
    collection.find({"_id": new ObjectId(request.params.id) }).toArray((error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        response.send(result);
    });
});
app.put("/customer/:id", (request, response) => {
    collection.updateOne({ "_id": new ObjectId(request.params.id) },{$set:request.body}, (error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        response.send(result.result);
    });
});
app.delete("/customer/:id", (request, response) => {
    collection.remove({ "_id": new ObjectId(request.params.id) }, (error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        response.send(result);
    });
});
app.post("/signup", (request, response) => {
    collection1.insert(request.body, (error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        response.send(result.result);
    });
});
app.post("/login", (request, response) => {
   
    collection1.findOne(request.body, (error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        var s ="";
        if(!result)
        {
            s = "0";
            console.log("login fail")
        }
        else
        {
            s = "1";
            console.log("login pass" + result)
        }
        const responseData = {
            message:s
        }
        response.send(responseData);
       
    });
});

Front End Part

Create a Project for React JS and Design Route(path) under APP.js

Code of App.js

import './App.css';
import React from 'react';
import {Route,Routes,BrowserRouter} from 'react-router-dom'
import Hello from './Hello.js'
import Login from './Login.js'
import Layout from './Layout';
import { FetchExample } from './FetchExample';
import EditCust from './EditCust';
import DeleteCust from './DeleteCust';
import FetchPostAPI from './FetchPostAPI';

function App() {
  return (
   
       <BrowserRouter>
        <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Hello />} />
          <Route path="hello" element={<Hello />} />
          <Route path="login" element={<Login />} />
          <Route path="customerdashboard" element={<FetchExample />} />
          <Route path="edit"  element={<EditCust />} />
          <Route path="delete"  element={<DeleteCust />} />
          <Route path="addcust"  element={<FetchPostAPI />} />
          </Route>
      </Routes>
    </BrowserRouter>
 
  );
}
export default App;
export default App;

APP Contain Login.JS Component , FetchExample to Create GRID, EditCust.JS to update record
and DeleteCust.js to delete the record.

Code for Login.js Component:=-

import React from "react";
import axios from "axios";
function Login()
{
 const baseURL = "http://127.0.0.1:5000/login";
  const [username, setUsername] = React.useState("");
 const [password, setPassword] = React.useState("");
 const handelInput =(e)=>{
    switch (e.target.id) {
      case "username":
        setUsername(e.target.value)
        break;
        case "password":
          setPassword(e.target.value)
          break;
       
        default:
          break;
    }
}
const changeSubmit =(e)=>{
    e.preventDefault()  
    axios
    .post(baseURL, {
      username: username,
      password: password,
     
    })
    .then((response) => {
        console.log(response.data);
        if(response.data.message == "1")
        {
           window.location='customerdashboard';
        }
        else
        {
            window.location = '/login';
        }
    });
    }
    return(
       <>       
          <form onSubmit={changeSubmit}>
           
           username <input type="text"  id='username'   onChange={handelInput} />
            <br />
             password <input type="text"  id='password'  onChange={handelInput}/>
            <br />
           
            <button type="submit" value="Submit">Submit</button>
        </form>
         
       </>
   );
}

export default Login;

Code for FetchExample.js:-

import React from "react"
import { Link } from "react-router-dom";

export class FetchExample extends React.Component
{
    constructor()

   {
    super();
    this.state = { tdata:[] }

   }
   componentDidMount()
   {
    fetch('http://127.0.0.1:5000/customer')

    .then(res => res.json())

    .then((data) => {

      this.setState({ tdata: data})

      console.log(this.state.tdata)

    }).catch(console.log)
  }
  render()
  {
    return(<div>
        <table boder='1'>
            <tr><th>Name</th><th>mobileno</th><th>Email</th><th>Address</th><th>Edit</th><th>Delete</th></tr>
            {this.state.tdata.map((person,i)=> <TableRow Key={i} data={person} />)}  
        </table>

    </div>)
  }
   
}
class TableRow extends React.Component
{
    render()
    {
        return(<tr>
            <td> {this.props.data.name}</td>
            <td> {this.props.data.mobileno}</td>
            <td> {this.props.data.email}</td>
            <td> {this.props.data.address}</td>
            <td><Link to="/edit" state={this.props.data._id} >Edit</Link></td>
            <td><Link to="/delete" state={this.props.data._id} >Delete</Link></td>
           
        </tr>)
    }
}
Code for EditCust.js:-

import React, { useState }   from 'react';
import { useLocation } from "react-router";
import axios from 'axios'
function EditCust()
{
 let data = useLocation();
 console.log(data.state);
 const baseURL = "http://127.0.0.1:5000/customer/"+data.state;
 const [post, setPost] = useState("");
 const [name,setName]= useState(undefined)
 const [email,setEmail]= useState(undefined)
 const [mobile,setMobile]= useState(undefined)
 const [address,setAddress]= useState(undefined)
React.useEffect(() => {
 axios.get(baseURL).then((response) => {

      setPost(response.data[0]);
      //console.log("Data is ",response.data[0].name);
      //console.log("Post data is ",post);

    });

  }, []);

  const handelName =(e)=>{
   
    setName(e.target.value)
}
const handelEmail =(e)=>{
   
    setEmail(e.target.value)

}
const handelMobile =(e)=>{
   
    setMobile(e.target.value)

}
const handelAddress =(e)=>{
   
    setAddress(e.target.value)
}
const changeSubmit =(e)=>{

   if(name==undefined)
   {
    setName(post.name)
   }
   if(email==undefined)
   {
    setEmail(post.email)
   }
   if(mobile==undefined)
   {
   setMobile(post.mobileno)
   }
   if(address==undefined)
   {
    setAddress(post.address)
   }
    axios.put(baseURL, {
      name: name,
      mobileno:mobile,
      email: email,
      address:address

    })
    .then((response) => {

     // setPost(response.data);

     window.location.href="/customerdashboard";

    });   

    e.preventDefault();  
}
  if (!post) return null;

   return(
       <div id="middle">
            <form onSubmit={changeSubmit}>
              <table>
              <tr>Name <td></td><td>  <input type="text"  id='name' defaultValue={post.name}  onChange={handelName}   />   </td></tr>
              <tr>Mobileno<td></td> <input type="text"  id='mobileno' defaultValue={post.mobileno}  onChange={handelMobile}       /> <td></td></tr>
              <tr>Email <td></td><td>  <input type="text"  id='email' defaultValue={post.email}   onChange={handelEmail} /></td></tr>
              <tr>Address<td></td><td><input type="text"  id='address' defaultValue={post.address} onChange={handelAddress}/></td></tr>
              <tr><td colSpan={2} align={'left'}><button type="submit" value="Submit">Submit</button></td></tr>
              </table>
              </form>
              </div>
   );
}
export default EditCust;

Code for DeleteCust.js

import React, { useState }   from 'react';
import { useLocation } from "react-router";
import axios from 'axios'
function DeleteCust()
{
 let data = useLocation();
 console.log(data.state);
 const baseURL = "http://127.0.0.1:5000/customer/"+data.state;
 const [post, setPost] = useState("");
 const [name,setName]= useState("")
 const [email,setEmail]= useState("")
 const [mobile,setMobile]= useState("")
 const [address,setAddress]= useState("")
 React.useEffect(() => {
    axios.get(baseURL).then((response) => {

      setPost(response.data[0]);
      //console.log("Data is ",response.data[0].name);
      //console.log("Post data is ",post);

    });

  }, []);
  const handelName =(e)=>{
   
    setName(e.target.value)
}
const handelEmail =(e)=>{
       setEmail(e.target.value)
}
const handelMobile =(e)=>{
   
    setMobile(e.target.value)
}
const handelAddress =(e)=>{
      setAddress(e.target.value)
}
const changeSubmit =(e)=>{
 
  axios

    .delete(baseURL) .then((response) => {

     // setPost(response.data);

     window.location.href="/customerdashboard";
    });
    e.preventDefault();  
}
  if (!post) return null;

   return(
       <div id="middle">
        <h1>Are you sure to delete the record?</h1>
         <form onSubmit={changeSubmit}>
            Name is {post.name}
            <br />
            Mobileno {post.mobileno}
            <br />  
            Email  {post.email}
            <br />
            Address {post.address}
            <br />
            <button type="submit" value="Submit">Delete</button>
         </form>
       
       </div>
   );
}
export default DeleteCust;
Code for Add Customer Record:-
import React, { useState }   from 'react';
import axios from 'axios'
function FetchPostAPI()
{
const baseURL = "http://127.0.0.1:5000/customer";
const [name,setName]= useState(undefined)
const [email,setEmail]= useState(undefined)
const [mobile,setMobile]= useState(undefined)
const [address,setAddress]= useState(undefined)
const handelName =(e)=>{
   setName(e.target.value)
}
const handelEmail =(e)=>{
   setEmail(e.target.value)
}
const handelMobile =(e)=>{
   setMobile(e.target.value)
}
const handelAddress =(e)=>{
   setAddress(e.target.value)
}
const changeSubmit =(e)=>{
  axios.post(baseURL, {
      name: name,
      mobileno:mobile,
      email: email,
      address:address}).then((response) => {
        window.location.href="/customerdashboard";
    });
    e.preventDefault();  
}
return(
<div id="middle">
            <form onSubmit={changeSubmit}>
              <table>
              <tr>Name <td></td><td>  <input type="text"  id='name'  onChange={handelName}   />   </td></tr>
              <tr>Mobileno<td></td> <input type="text"  id='mobileno' onChange={handelMobile}       /> <td></td></tr>
              <tr>Email <td></td><td>  <input type="text"  id='email'   onChange={handelEmail} /></td></tr>
              <tr>Address<td></td><td><input type="text"  id='address' onChange={handelAddress}/></td></tr>
              <tr><td colSpan={2} align={'left'}><button type="submit" value="Submit">Submit</button></td></tr>
              </table>
              </form>
              </div>   );
}
export default FetchPostAPI;

Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...