In a MERN stack (MongoDB, Express, React, Node.js)
, the frontend (React)
interacts with the backend (Node.js + Express)
primarily through HTTP
requests. The backend handles these requests, processes them (often involving interactions with a database
like MongoDB
), and returns a response to the frontend.
How the Frontend (React) and Backend (Node.js/Express) Interact:
1. Frontend (React):
- The frontend is responsible for displaying the user interface, handling user input, and making HTTP requests to the backend when it needs data or to perform actions (such as submitting a form).
- In technically terms, we call frontend as
client
, it can be anything your web application, mobile application or any user facing application. - Client talk via APIs to the server(backend).
-
React
uses libraries likeAxios
or the nativeFetch API
to make HTTP requests (GET, POST, PUT, DELETE, etc.) to the backend.
2. Backend (Node.js +Express):
- The backend (Express) receives the HTTP requests from the frontend, processes them (such as fetching or modifying data from MongoDB), and sends back a response, which could be data (JSON) or an acknowledgment of the operation.
- These fetch calls have routes(like /product, /home, /profile, or ...) and all the code for these routes will be written in Express.
- Express also known as
routing library
, but it's more accurate to call it aweb application framework
forNode.js
. It provides a set of tools that make it easier to build web applications and APIs, and one of its core functionalities is routing. - Server talks database, to get data or to send data by queries (like find, findOne, findById, findByIdAndDelete, findByIdAndUpdate or more queries).
- The backend typically exposes routes (API endpoints) for the frontend to call.
3. Database (MongoDB):
- MongoDB is a NoSQL database where data is stored in collections and documents. The backend uses MongoDB to store and retrieve data in response to requests from the frontend.
- The most commonly used ODM
(Object Data Modeling)
for MongoDB in Node.js applications is Mongoose. -
Mongoose
is an ODM library that provides a straightforward way to interact with MongoDB from a Node.js environment. It allows you to define data schemas, validate data, perform CRUD (Create, Read, Update, Delete) operations, and more, in an object-oriented way.
Example: Frontend (React) Making a GET Request to Backend (Express) to Fetch Data
- Backend (Express):
Let's start by setting up a basic Express server with one API endpoint to get a list of items from the database.
server.js(Backend)
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = 5000;
// Use CORS to allow requests from the frontend
app.use(cors());
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/mern-demo',
{
useNewUrlParser: true,
useUnifiedTopology: true
});
// Sample MongoDB schema and model
const Item = mongoose.model('Item', new mongoose.Schema({ name: String }));
// Route to fetch items from MongoDB
app.get('/api/items', async (req, res) => {
try {
const items = await Item.find();
res.json(items); // Send items as JSON response
} catch (err) {
res.status(500).send('Server Error');
}
});
// Route to Add items to MongoDB
app.post('/api/items', async (req, res) => {
const { name } = req.body; // Extract 'name' from request body
try {
const newItem = new Item({ name });
await newItem.save(); // Save the item to MongoDB
res.json(newItem); // Send the saved item back as a response
} catch (err) {
res.status(500).send('Server Error');
}
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
- Frontend (React):
Now, on the frontend (React), we can make a GET request to this API to fetch the items.
App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [items, setItems] = useState([]);
useEffect(() => {
// Fetch data from the backend
axios.get('http://localhost:5000/api/items')
.then(response => {
setItems(response.data); // Set items to state
})
.catch(error => {
console.error('There was an error fetching the items!', error);
});
}, []); // Empty array means this effect runs only once when the component mounts
return (
<div>
<h1>Item List</h1>
<ul>
{items.map(item => (
<li key={item._id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default App;
CreateItems.js
import React, { useState } from 'react';
import axios from 'axios';
const CreateItems = () => {
const [name, setName] = useState('');
const addItem = async () => {
try {
const response = await axios.post('http://localhost:5000/api/items', { name });
console.log('Item added:', response.data);
setName(''); // Reset input field
} catch (error) {
console.error('There was an error adding the item!', error);
}
};
return (
<div>
<h1>Add Item</h1>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter item name"
/>
<button onClick={addItem}>Add Item</button>
</div>
);
}
export default CreateItems;
Explanation:
1. Backend (Express) Setup:
- The backend has a two routes, one get(/api/items) that fetches a list of items and second post(/api/items) create a item to the MongoDB database using Mongoose.
- The Item model is a simple schema that has a name field (you can add more fields as per your requirement).
- The server listens on port 5000, and CORS is enabled to allow requests from the React frontend (which typically runs on port 3000 in development).
2. Frontend (React) Setup:
- In the App.js file, the useEffect hook is used to fetch data when the component mounts (i.e., when the app is first loaded).
- The axios.get method is used to make an HTTP GET request to the backend's /api/items endpoint.
- When the data is fetched, it's stored in the component's state (items), and the list of items is rendered in an unordered list.
3. CORS:
- CORS (Cross-Origin Resource Sharing) is enabled in the Express server to allow the React frontend to make requests to the backend even though they are running on different ports (React usually runs on port 3000, while Express runs on port 5000).
Summary:
- The React frontend makes HTTP requests (GET, POST, etc.) to the Express backend.
- The Express server handles the requests, interacts with the MongoDB database, and sends responses (data or acknowledgment) back to the frontend.
- This communication typically happens via RESTful APIs exposed by the backend.
Top comments (0)