AI Technology world ๐ŸŒ

Building an e-commerce website for a clothing store requires several components, including frontend, backend, and database management. Below is a complete guide to building an e-commerce website using React.js (Frontend), Node.js with Express (Backend), and MongoDB (Database).


Step 1: Set Up the Project

Install Dependencies

mkdir clothing-store cd clothing-store npx create-react-app frontend mkdir backend cd backend npm init -y


Step 2: Backend (Node.js, Express, MongoDB)

1. Install Required Packages

npm install express mongoose cors dotenv bcryptjs jsonwebtoken multer multer-s3 aws-sdk

2. Create server.js

import express from 'express'; import dotenv from 'dotenv'; import mongoose from 'mongoose'; import cors from 'cors'; dotenv.config(); const app = express(); app.use(cors()); app.use(express.json()); // Connect to MongoDB mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log('MongoDB Connected')) .catch(err => console.log(err)); // Routes import productRoutes from './routes/productRoutes.js'; import userRoutes from './routes/userRoutes.js'; app.use('/api/products', productRoutes); app.use('/api/users', userRoutes); const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));


Step 3: Database Models

1. User Model (models/User.js)

import mongoose from 'mongoose'; const userSchema = new mongoose.Schema({ name: String, email: { type: String, unique: true }, password: String, isAdmin: { type: Boolean, default: false } }); export default mongoose.model('User', userSchema);

2. Product Model (models/Product.js)

import mongoose from 'mongoose'; const productSchema = new mongoose.Schema({ name: String, price: Number, description: String, imageUrl: String, category: String, stock: Number }); export default mongoose.model('Product', productSchema);


Step 4: API Routes

1. User Routes (routes/userRoutes.js)

import express from 'express'; import bcrypt from 'bcryptjs'; import jwt from 'jsonwebtoken'; import User from '../models/User.js'; const router = express.Router(); // Register router.post('/register', async (req, res) => { const { name, email, password } = req.body; const hashedPassword = await bcrypt.hash(password, 10); const user = new User({ name, email, password: hashedPassword }); await user.save(); res.json({ message: 'User registered successfully' }); }); // Login router.post('/login', async (req, res) => { const { email, password } = req.body; const user = await User.findOne({ email }); if (!user) return res.status(400).json({ error: 'Invalid credentials' }); const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ error: 'Invalid credentials' }); const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' }); res.json({ token, user }); }); export default router;

2. Product Routes (routes/productRoutes.js)

import express from 'express'; import Product from '../models/Product.js'; const router = express.Router(); // Get all products router.get('/', async (req, res) => { const products = await Product.find(); res.json(products); }); // Add a product router.post('/', async (req, res) => { const product = new Product(req.body); await product.save(); res.json(product); }); export default router;


Step 5: Frontend (React.js)

1. Install Dependencies

cd frontend npm install axios react-router-dom redux react-redux redux-thunk bootstrap

2. Setup React Router (src/App.js)

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import HomeScreen from './screens/HomeScreen'; import ProductScreen from './screens/ProductScreen'; import LoginScreen from './screens/LoginScreen'; function App() { return ( <Router> <Routes> <Route path="/" element={<HomeScreen />} /> <Route path="/product/:id" element={<ProductScreen />} /> <Route path="/login" element={<LoginScreen />} /> </Routes> </Router> ); } export default App;

3. Fetch Products (src/screens/HomeScreen.js)

import { useEffect, useState } from 'react'; import axios from 'axios'; const HomeScreen = () => { const [products, setProducts] = useState([]); useEffect(() => { axios.get('http://localhost:5000/api/products') .then(response => setProducts(response.data)) .catch(error => console.log(error)); }, []); return ( <div> <h1>Clothing Store</h1> <div> {products.map(product => ( <div key={product._id}> <h3>{product.name}</h3> <p>{product.price}$</p> </div> ))} </div> </div> ); }; export default HomeScreen;


Step 6: Run the Project

1. Start Backend

cd backend node server.js

2. Start Frontend

cd frontend npm start


Step 7: Deployment

For deployment, use:

  • Backend: Host on Render, Heroku, or AWS.
  • Frontend: Deploy on Vercel or Netlify.
  • Database: Use MongoDB Atlas.

Bonus: Adding Payment (Stripe)

To integrate Stripe payments:

  1. Install Stripe: npm install stripe
  2. Add checkout in the backend and frontend.
  3. Use Stripe’s checkout session API.

Conclusion

This is a basic e-commerce clothing store. You can further enhance it by adding:

  • Admin Dashboard
  • User Authentication with JWT
  • Cart & Order Management
  • Search & Filters

Would you like any additional features or modifications?

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *

PHP Code Snippets Powered By : XYZScripts.com