Now you connect React (Frontend) with Node.js/Express (Backend). This is the core of full-stack development. Frontend sends HTTP requests โ Backend processes โ Returns JSON data.
๐ง How Frontend and Backend Communicate
Flow:
1๏ธโฃ React sends request (API call)
2๏ธโฃ Backend receives request
3๏ธโฃ Backend processes logic
4๏ธโฃ Backend sends response
5๏ธโฃ React updates UI
Example: React โ GET /users โ Express API โ JSON โ React UI
๐ API Request Methods Used in React
- GET: Fetch data
- POST: Send data
- PUT: Update data
- DELETE: Remove data
โก Method 1: Fetch API
JavaScript has a built-in function called fetch().
๐ฅ Example: Fetch users from backend
Backend endpoint: GET
http://localhost:3000/usersReact code:
import { useEffect, useState } from "react";
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("http://localhost:3000/users")
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
<div>
<h2>User List</h2>
{users.map(user => (
<p key={user.id}>{user.name}</p>
))}
</div>
);
}
export default App;
Result: React automatically displays backend data.โ Sending Data to Backend (POST)
Example: Add new user.
const addUser = async () => {
await fetch("http://localhost:3000/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "Deepak" })
});
};
Backend receives JSON and stores it.โ๏ธ Updating Data (PUT)
await fetch("http://localhost:3000/users/1", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "Updated Name" })
});
โ Deleting Data (DELETE)await fetch("http://localhost:3000/users/1", {
method: "DELETE"
});
๐งฉ Common Full Stack Folder Structureproject/Frontend and backend run separately.
โโโ client/ (React frontend)
โ โโโ src/
โโโ server/ (Node backend)
โ โโโ routes/
โโโ package.json
โ ๏ธ Common Beginner Issues
1๏ธโฃ CORS error
Backend must allow frontend.
Example:
const cors = require("cors");
app.use(cors());
Install: npm install cors2๏ธโฃ Wrong API URL
Frontend must call:
http://localhost:3000/api/users3๏ธโฃ Missing JSON middleware
app.use(express.json())๐งช Mini Practice Task
Build a simple React + Express full stack app
Tasks:
- Fetch users from backend
- Display users in React
- Add new user from React form
- Delete user from UI
โก๏ธ Double Tap โฅ๏ธ For More