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;
POST Answer of Questions and ASK to Doubt