Skip to main content

Frontend Backend Integration

Client and Server File Folder Structure​

This file folder structure for a client-server application. Such a structure helps organize and manage code and resources efficiently.

client
server

Client​

The client-side of the application is responsible for the user interface and handling user interactions.

/src (Source Code)​

  • /components: Contains reusable React components.
  • /views: This is where you store components and files that are unique to specific pages or sections of your app.
  • /pages: Each page or view of the application has its folder here.
  • /utils: Utility functions used throughout the client-side application.

/public​

  • index.html: The main HTML file for the client.

/config​

  • config.js: Configuration files for client-side settings and constants.

/build​

  • Compiled and optimized code for production.

Server​

The server-side handles business logic, communicates with the database, and serves API endpoints to the client.

/src (Source Code)​

  • /controllers: Controllers that handle HTTP requests and responses.
  • /models: Database models and schemas.
  • /routes: Define API routes and endpoints.
  • /middleware: Custom middleware for handling requests and responses.
  • /config: Server configuration files.
  • /utils: Utility functions used on the server-side.

/node_modules​

  • Auto-generated folder for storing project dependencies.

/logs​

  • Log files generated by the server for debugging and monitoring.

/config​

  • Server configuration files, including environment-specific settings.

.gitignore​

  • Specifies files and directories to be ignored by version control.

package.json​

  • Lists project dependencies and scripts for starting, building, and testing the application.

README.md​

  • Project documentation, providing an overview, setup instructions, and other important information.

.env​

  • Environment variables for configuring the application.

.env.example​

  • An example environment variables file, useful for setting up local development.

This folder structure is just a template and can be adapted to suit the specific needs and technologies of your client-server application.

Using Axios to Call the API in a React App​

To call the API from a React app, you can use the Axios library, which is a popular choice for making HTTP requests.

Here's how you can set up and use Axios in a React app:

  1. Create a new React app by running the following command in your terminal:
npx create-react-app .
  1. Install the Axios library by running the following command in the terminal:
npm install axios
  1. Open the App.js file in the src directory of your React app.

  2. Import the Axios library at the top of the file:

import axios from "axios";
  1. Create an async function, let's name it loadData, inside the App component:
async function loadData() {
const response = await axios.get("/student");
console.log(response)
}

To call API's in react app.

Firstly you have create simple react app.

npx create-react-app frontend

Then install axiox library for calling frontend API's in the react app.In the react app remove unwanted content from App.js file.Then create async function and set proxy in package.json file.

 "proxy": "http://localhost:5000"

Add Student Form​

client/src/views/AddStudent
import React, { useState } from 'react';
import axios from 'axios';
import './AddStudent.css'

export default function AddStudent() {
const [name, setName] = useState('')
const [age, setAge] = useState('')
const [mobile, setMobile] = useState('');
const [email, setEmail] = useState('');

const addToStudent = async () => {

const addstudent = {
name,
age,
mobile,
email
}
await axios.post('/student', addstudent)
setName('');
setAge('');
setMobile('');
setEmail('');
}
return (
<div>
<div className='maindiv'>
<h1>Add Student</h1>

<form>
<input type='text' value={name} placeholder='product name' onChange={(e) => {
setName(e.target.value)
}} className='input-box' />

<input type='text' value={age} placeholder='enter age' onChange={(e) => {
setAge(e.target.value)
}} className='input-box' />

<input type='text' value={mobile} placeholder='enter mobile' onChange={(e) => {
setMobile(e.target.value)
}} className='input-box' />

<input type='text ' value={email} placeholder='enter email' onChange={(e) => {
setEmail(e.target.value)
}} className='input-box' />

<button type='button' onClick={addToStudent} className='input-box butn'> Add Student</button>
</form>
</div>
</div>
)
}

Home Page with Student List​

client/src/views/Home
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import './Home.css'

function Home() {
const [student, setStudent] = useState([])

const loadStudent = async () => {
const response = await axios.get("/students");
setStudent(response?.data?.data);
}
useEffect(() => {
loadStudent();
}, [])

const deleteStudent = async (id) =>{
const response = await axios.delete(`/student/${id}`)
if(response?.data?.data){
loadStudent();
}
}

return (
<div>
<h1>Home</h1>
<div className='flex'>
{
student.map((product, index) => {
const { name, age, mobile, email} = product
return (<>
<div key="index" className='student-card'>
<p> Student Name: <span>{name}</span></p>
<p> Age: <span>{age}</span> </p>
<p>Mobile: <span>{mobile}</span></p>
<p> Email:<span>{email}</span></p>
<a href={`/student-detail/${_id}`} target='_blank'>View More</a>
<button type='button' onClick={()=>{deleteStudent(_id)}} >delete</button>

<a href={`/update-student/$(_id)`} target= '_blank'className="btn-edit-student" >edit</a>
</div>
</>)
})
}
</div>
</div>
)
}

export default Home

Update Student Form​

client/src/views/UpdateStudent
import React, { useState useEffect } from 'react';
import axios from 'axios';
import './UpdateStudent.css';
import { useParams } from 'react-router-dom';


export default function UpdateStudent() {
const [name, setName] = useState('')
const [age, setAge] = useState('')
const [mobile, setMobile] = useState('');
const [email, setEmail] = useState('');

const {_id} = useParams();

const loadStudent =async () =>{
const response = await axios.get(`/student/${_id}`)
const { name, age, mobile,email } = response?.data?.data
setName(name)
setAge(age)
setMobile(mobile)
setEmail(email)
}

useEffect(()=>{
loadStudent();
},[])

const updateToStudent = async () => {

const updatedDetails = {name, age, mobile,email}
const response = await axios.put(`/student/${id}`, updatedDetails)

alert(response.data.message)
}

return (
<div>
<div className='maindiv'>
<h1>Update Student</h1>

<form>
<input type='text' value={name} placeholder='product name' onChange={(e) => {
setName(e.target.value)
}} className='input-box' />

<input type='text' value={age} placeholder='enter age' onChange={(e) => {
setAge(e.target.value)
}} className='input-box' />

<input type='text' value={mobile} placeholder='enter mobile' onChange={(e) => {
setMobile(e.target.value)
}} className='input-box' />

<input type='text ' value={email} placeholder='enter email' onChange={(e) => {
setEmail(e.target.value)
}} className='input-box' />

<button type='button' onClick={updateToStudent} className='input-box butn'> Update Student</button>
</form>
</div>
</div>
)
}

Routing Configuration​

client/src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import Home from './views/Home/Home'
import AddStudent from './views/AddStudent/AddStudent'
import './index.css';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import StudentDetail from './views/StudentDetail/StudentDetail';
import UpdateStudent from './views/UpdateStudent/UpdateStudent';


const root = ReactDOM.createRoot(document.getElementById('root'));
const router = createBrowserRouter([
{
path:"/",
element:<Home />
},
{
path:"/add-student" ,
element:<AddStudent />
},
{
path:"/update-student/:id",
element:<UpdateStudent />
},
{
path:'/student-detail/:id',
element:<StudentDetail />
}
])

root.render(
<RouterProvider router={router} />
);

Server Route for Retrieving a Student's Information​

app.get('/student/:_id' , async(req,res) =>{
const {_id} = req.params
const findingOneStudent = await Student.findOne({_id:_id})
res.json({
data:findingOneProduct
})
})

Student Detail Page with Axios Data Fetching​

import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import './StudentDetail.css'

const StudentDetail = () => {
const [ student,setStudent] = useState({})

const loadstudent = async () =>{
const response = await axios.get('/student/${_id}');
setStudent(response?.data?.data);
}
useEffect(()=>{
loadstudent();
},[])

const {_id} = useParams();
const{name, mobile, age, email} = student
return (
<div>
<h1>Student Detail</h1>
<div className='student-card'>
<div>
<h1>Name: {name}</h1>
<p>Mobile : {mobile}</p>
<p>Age :{age}</p>
<p>Email: {email}</p>
</div>
</div>
</div>
)
}

export default StudentDetail