The MERN stack is a popular JavaScript stack used for building full-stack web applications. MERN stands for MongoDB, Express, React, and Node.js.
Each technology in the MERN stack has a specific role in building a scalable, high-performance web application. MongoDB is a NoSQL database that stores data
in a flexible, JSON-like format. Express is a web application framework for Node.js that simplifies handling HTTP requests and responses. React is a front-end library
for building user interfaces. Finally, Node.js allows JavaScript to be executed on the server-side.
Components interaction in MERN Stack:
1. MongoDB: The data layer, stores application data in a flexible format, and communicates with the backend server (Node.js) using queries.
2. Express: Acts as the server-side framework, handling HTTP requests, interacting with MongoDB, and sending responses to the React frontend.
3. React: Handles the UI, and communicates with Express to retrieve data from MongoDB or submit data via forms.
4. Node.js: Bridges the backend and frontend using JavaScript, enabling the use of JavaScript throughout the stack.
Here is a simple example showing how these components interact:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = 5000;
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/mern_example', { useNewUrlParser: true, useUnifiedTopology: true });
// Middleware to parse JSON data
app.use(express.json());
// Define a schema and a model for MongoDB
const UserSchema = new mongoose.Schema({
name: String,
email: String,
});
const User = mongoose.model('User', UserSchema);
// Define routes for Express
app.get('/api/users', async (req, res) => {
const users = await User.find({});
res.json(users);
});
app.post('/api/users', async (req, res) => {
const newUser = new User(req.body);
await newUser.save();
res.json(newUser);
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Leave a Reply