FULLSTACK MERN BASIC
🌐 Fullstack MERN – Complete Core Notes
MongoDB, Express.js, React.js aur Node.js ka end-to-end full-stack integration guide.
1️⃣ MERN Kya Hai?
Definition: MERN ek powerful, full-stack JavaScript software stack hai jo modern, dynamic aur fast web applications banane ke liye use hota hai.
| Letter | Technology | Layer / Role | Primary Task |
|---|---|---|---|
| M | MongoDB | Database Layer | Flexible JSON-like NoSQL documents me data store karna. |
| E | Express.js | Backend Web Framework | Server routing, middlewares aur RESTful APIs manage karna. |
| R | React.js | Frontend UI Library | Interactive Single Page Application (SPA) user interface render karna. |
| N | Node.js | Backend Runtime | V8 engine par server-side JavaScript code execute karna. |
2️⃣ Standard Project Folder Structure
Production-ready MERN project ko clean separation of concerns ke liye divide kiya jata hai:
mern-app/
├── backend/ # Node.js + Express Server
│ ├── models/ # Mongoose Schemas (Database Models)
│ ├── routes/ # Express API Route Handlers
│ ├── controllers/ # Business Logic Handlers
│ ├── .env # Database URI & Secret Keys
│ └── server.js # Server Entry Point
└── frontend/ # React Application (Vite / CRA)
├── src/
│ ├── components/ # Reusable UI Components
│ ├── pages/ # View Pages
│ └── App.jsx # Main React Component
└── package.json
3️⃣ Backend Setup (Node + Express + MongoDB)
Backend directory initialize karein aur required packages install karein:
mkdir backend && cd backend
npm init -y
npm install express mongoose cors dotenv
Complete Server Code (server.js):
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
// Middlewares
app.use(cors()); // Cross-Origin Requests allow karne ke liye
app.use(express.json()); // Incoming JSON body parse karne ke liye
// MongoDB Database Connection
mongoose.connect('mongodb://127.0.0.1:27017/studentDB')
.then(() => console.log('MongoDB Connected Successfully!'))
.catch(err => console.error('Connection Error:', err));
// Test API Route
app.get('/api/health', (req, res) => {
res.json({ status: 'Server Active', timestamp: new Date() });
});
// Port Listen
const PORT = 5000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
4️⃣ MongoDB Model (Mongoose Schema)
Database me documents ka strict blueprint define karne ke liye Mongoose Schema create kiya jata hai (models/Student.js):
const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
enrolled: {
type: Boolean,
default: true
}
}, { timestamps: true });
module.exports = mongoose.model('Student', studentSchema);
5️⃣ Frontend Setup (React Application)
Naya React project setup karein aur API calls ke liye axios install karein:
npx create-react-app frontend
cd frontend
npm install axios
npm start
React Component (Fetching Data from Backend):
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [students, setStudents] = useState([]);
useEffect(() => {
// Backend API Call
axios.get('http://localhost:5000/api/students')
.then(response => setStudents(response.data))
.catch(error => console.error('Fetch Error:', error));
}, []);
return (
<div style={{ padding: '20px' }}>
<h1>Student Registry (MERN)</h1>
<ul>
{students.map(s => (
<li key={s._id}>{s.name} - Age: {s.age}</li>
))}
</ul>
</div>
);
}
export default App;
6️⃣ Client ↔ Server Fullstack Data Pipeline
Frontend se backend API call karne ke do standard approaches hote hain:
| Method | Syntax Preview | Pros |
|---|---|---|
| Fetch API | fetch(url).then(res => res.json()) |
Native browser method, koi external package download nahi karna padta. |
| Axios | axios.get(url).then(res => res.data) |
Automatic JSON parsing, automatic error handling aur cleaner syntax. |
cors middleware lazmi add karein: const cors = require('cors'); app.use(cors());.