This tutorial will teach you how to make Crud Application using Node JS with React Frontend application and Mongo DB Database using Api access Crudapplication.
First Step What you have to do is you to divide the Front-End and Back-End.
Front-End – React
BackEnd – Node JS
Create the folder myprojects. inside the folder Frond end project you maintaining with the separate folder.
Backend project you maintaining with the separate folder.
Install Node JS
Create a new Project type the command on the command prompt.
Type the Command on Console.
npm init
and create your project. After project has been created you see the package.json file.
Then open the project in to the VS Code Editor by typing the following command
code .
after open up the project in to the vscode editor
Install the Express Server as back end server
npm i express
Install the mongoDB as database
npm i express
First Create the Application server.js which manage the ports and libraries and database connection of the project.
we have created the datbase on mongoDB Compass which name est.
attached the db connection below.
server.js
var express = require('express'); var server = express(); var routes = require('./routes/routes'); var mongoose = require('mongoose'); const cors = require('cors'); mongoose.connect("mongodb://localhost:27017/est",{useNewUrlParser: true, useUnifiedTopology: true },function checkDB(error) { if(error) { console.log("errorr") } else { console.log("DB Connectedddd!!!!!!!!!!!") } }); server.use(cors()); server.use(express.json()); server.use(routes); server.listen(8000,function check(error) { if(error) { console.log("errorr") } else { console.log("startedddddd") } });
After that you can run the server type by the following command.
node server.js
You can get the result as
DB Connectedddd
startedddddd
after that make the new folder route and inside the folder create the page route.js. route.js page which use to manage the all the restapis related to crud operations.
var express = require('express'); const router = express.Router(); var userController = require('../src/user/userController'); router.route('/user/getAll').get(userController.getDataConntrollerfn); router.route('/user/create').post(userController.createUserControllerFn); router.route('/user/update/:id').patch(userController.updateUserController); router.route('/user/delete/:id').delete(userController.deleteUserController); module.exports = router;
After that create the MVC Page.First Create the Controller Page
userController.js
var userService = require('./userService'); var getDataConntrollerfn = async (req, res) => { var empolyee = await userService.getDataFromDBService(); res.send({ "status": true, "data": empolyee }); } var createUserControllerFn = async (req, res) => { var status = await userService.createUserDBService(req.body); if (status) { res.send({ "status": true, "message": "User created successfully" }); } else { res.send({ "status": false, "message": "Error creating user" }); } } var updateUserController = async (req, res) => { console.log(req.params.id); console.log(req.body); var result = await userService.updateUserDBService(req.params.id,req.body); if (result) { res.send({ "status": true, "message": "User Updateeeedddddd"} ); } else { res.send({ "status": false, "message": "User Updateeeedddddd Faileddddddd" }); } } var deleteUserController = async (req, res) => { console.log(req.params.id); var result = await userService.removeUserDBService(req.params.id); if (result) { res.send({ "status": true, "message": "User Deleteddd"} ); } else { res.send({ "status": false, "message": "User Deleteddd Faileddddddd" }); } } module.exports = { getDataConntrollerfn, createUserControllerFn,updateUserController,deleteUserController };
userService.js
var userModel = require('./userModel'); module.exports.getDataFromDBService = () => { return new Promise(function checkURL(resolve, reject) { userModel.find({}, function returnData(error, result) { if (error) { reject(false); } else { resolve(result); } }); }); } module.exports.createUserDBService = (userDetails) => { return new Promise(function myFn(resolve, reject) { var userModelData = new userModel(); userModelData.name = userDetails.name; userModelData.address = userDetails.address; userModelData.phone = userDetails.phone; userModelData.save(function resultHandle(error, result) { if (error) { reject(false); } else { resolve(true); } }); }); } module.exports.updateUserDBService = (id,userDetails) => { console.log(userDetails); return new Promise(function myFn(resolve, reject) { userModel.findByIdAndUpdate(id,userDetails, function returnData(error, result) { if(error) { reject(false); } else { resolve(result); } }); }); } module.exports.removeUserDBService = (id) => { return new Promise(function myFn(resolve, reject) { userModel.findByIdAndDelete(id, function returnData(error, result) { if(error) { reject(false); } else { resolve(result); } }); }); }
userModel.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ name: { type: String, required: true }, address: { type: String, required: true }, phone: { type: String, required: true } }); module.exports = mongoose.model('employees', userSchema);
React
Installing React
npx create-react-app frontend-app
After complete the installation and run the project using following command.
npm start run
Now you see the React Welcome Page.
After that open the React project into VS code editor.
After that install the Bootstrap by typing the following command
npm i bootstrap
After that install the axios by typing the following command
npm i axios
Creating a new Component EmployeeCrud.js
import axios from "axios";
import { useEffect, useState } from "react";
function EmployeeCrud() {
const [_id, setId] = useState("");
const [name, setName] = useState("");
const [address, setAddress] = useState("");
const [phone, setMobile] = useState("");
const [employees, setUsers] = useState([]);
useEffect(() => {
(async () => await Load())();
}, []);
async function Load() {
const result = await axios.get("http://localhost:8000/user/getAll");
setUsers(result.data.data);
console.log(result.data);
}
async function save(event) {
event.preventDefault();
try {
await axios.post("http://localhost:8000/user/create", {
name: name,
address: address,
phone: phone,
});
alert("Employee Registation Successfully");
setId("");
setName("");
setAddress("");
setMobile("");
Load();
} catch (err) {
alert("User Registation Failed");
}
}
async function editEmployee(employees) {
setName(employees.name);
setAddress(employees.address);
setMobile(employees.phone);
setId(employees._id);
}
async function DeleteEmployee(_id) {
await axios.delete("http://localhost:8000/user/delete/" + _id);
alert("Employee deleted Successfully");
Load();
}
async function update(event) {
event.preventDefault();
try {
await axios.patch(
"http://localhost:8000/user/update/" +
employees.find((u) => u._id === _id)._id || _id,
{
_id: _id,
name: name,
address: address,
phone: phone,
}
);
alert("Registation Updateddddd");
setId("");
setName("");
setAddress("");
setMobile("");
Load();
} catch (err) {
alert(err);
}
}
return (
<div>
<h1>Employee Details</h1>
<div class="container mt-4">
<form>
<div class="form-group">
<input
type="text"
class="form-control"
id="_id"
hidden
value={_id}
onChange={(event) => {
setId(event.target.value);
}}
/>
<label>Employee Name</label>
<input
type="text"
class="form-control"
id="name"
value={name}
onChange={(event) => {
setName(event.target.value);
}}
/>
</div>
<div class="form-group">
<label>Employee Address</label>
<input
type="text"
class="form-control"
id="address"
value={address}
onChange={(event) => {
setAddress(event.target.value);
}}
/>
</div>
<div class="form-group">
<label>Mobile</label>
<input
type="text"
class="form-control"
id="phone"
value={phone}
onChange={(event) => {
setMobile(event.target.value);
}}
/>
</div>
<div>
<button class="btn btn-primary mt-4" onClick={save}>
Register
</button>
<button class="btn btn-warning mt-4" onClick={update}>
Update
</button>
</div>
</form>
</div>
<table class="table table-dark" align="center">
<thead>
<tr>
<th scope="col">Employee Id</th>
<th scope="col">Employee Name</th>
<th scope="col">Employee Address</th>
<th scope="col">Employee Mobile</th>
<th scope="col">Option</th>
</tr>
</thead>
{employees.map(function fn(employee) {
return (
<tbody>
<tr>
<th scope="row">{employee._id} </th>
<td>{employee.name}</td>
<td>{employee.address}</td>
<td>{employee.phone}</td>
<td>
<button
type="button"
class="btn btn-warning"
onClick={() => editEmployee(employee)}
>
Edit
</button>
<button
type="button"
class="btn btn-danger"
onClick={() => DeleteEmployee(employee._id)}
>
Delete
</button>
</td>
</tr>
</tbody>
);
})}
</table>
</div>
);
}
export default EmployeeCrud;