Sure! Here's an example code for a simple e-commerce platform using the MERN stack (MongoDB, Express.js, React, Node.js):
- Server-side (Backend) - Node.js + Express.js:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
// Middleware
app.use(bodyParser.json());
// Connect to MongoDB
mongoose
.connect("mongodb://localhost/ecommerce", { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.log(err));
// Routes
const productRoutes = require("./routes/productRoutes");
app.use("/api/products", productRoutes);
// Start the server
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
- Create a product route file in the "routes" folder (productRoutes.js):
const express = require("express");
const router = express.Router();
const Product = require("../models/Product");
// Get all products
router.get("/", (req, res) => {
Product.find()
.then((products) => res.json(products))
.catch((err) => res.status(400).json("Error: " + err));
});
// Create a new product
router.post("/", (req, res) => {
const { name, price } = req.body;
const newProduct = new Product({
name,
price,
});
newProduct
.save()
.then(() => res.json("Product added successfully!"))
.catch((err) => res.status(400).json("Error: " + err));
});
module.exports = router;
- Create a product model file in the "models" folder (Product.js):
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
});
module.exports = mongoose.model("Product", productSchema);
- Client-side (Frontend) - React.js:
-
Create a new React project using create-react-app command, and navigate to the project directory.
-
Replace the contents of "src/App.js" with the following code:
import React, { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [products, setProducts] = useState([]);
const [name, setName] = useState("");
const [price, setPrice] = useState(0);
useEffect(() => {
axios.get("/api/products").then((response) => {
setProducts(response.data);
});
}, []);
const addProduct = () => {
axios
.post("/api/products", { name, price })
.then(() => {
alert("Product added successfully!");
setName("");
setPrice(0);
})
.catch((err) => console.log(err));
};
return (
<div>
<h1>E-commerce Platform</h1>
<div>
<h2>Add a New Product</h2>
<input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Product Name" />
<input type="number" value={price} onChange={(e) => setPrice(e.target.value)} placeholder="Product Price" />
<button onClick={addProduct}>Add Product</button>
</div>
<div>
<h2>Product List</h2>
{products.map((product) => (
<div key={product._id}>
<p>{product.name}</p>
<p>{product.price}</p>
</div>
))}
</div>
</div>
);
}
export default App;
- Start the React development server using npm start or yarn start.
Make sure to install the required dependencies (express, mongoose, axios, etc.) by running npm install or yarn install.
This is a basic example to demonstrate the integration between the backend and frontend using the MERN stack. You can further enhance the code and add additional functionalities as per your project requirements.