Develope a complete shoe ordering site Need both front end and back end
- User
Develope a complete shoe ordering site Need both front end and back end
- Assistant
Creating a complete shoe ordering website involves developing both the front end (user interface) and the back end (server, database, API). Below is a step-by-step guide to building a basic full-stack shoe ordering website using the MERN stack (MongoDB, Express.js, React.js, Node.js). This guide covers setting up the development environment, creating the back end and front end, and connecting them together.
Table of Contents
- Prerequisites
- Project Structure
- Setting Up the Back End
- Initializing the Project
- Installing Dependencies
- Setting Up MongoDB
- Creating the Server with Express.js
- Defining Models (Product & Order)
- Creating API Routes
- Testing the API
- Setting Up the Front End
- Initializing the React Project
- Installing Dependencies
- Creating Components
- Product Listing
- Product Detail
- Shopping Cart
- Checkout
- Connecting to the Back End
- Styling the Application
- Running the Application
- Deployment
- Conclusion
Prerequisites
Ensure you have the following installed on your machine:
- Node.js & npm: Download and Install Node.js
- MongoDB: Download and Install MongoDB
- Git: Download and Install Git
- Code Editor: VS Code is recommended. Download VS Code
Project Structure
shoe-ordering-site/ ├── backend/ │ ├── models/ │ ├── routes/ │ ├── .env │ ├── server.js │ └── package.json ├── frontend/ │ ├── public/ │ ├── src/ │ │ ├── components/ │ │ ├── App.js │ │ └── index.js │ └── package.json ├── README.md └── .gitignore
Setting Up the Back End
1. Initialize the Project
Create a new directory for the project and navigate into it:
mkdir shoe-ordering-site cd shoe-ordering-siteCreate a
backendfolder:mkdir backend cd backendInitialize a new Node.js project:
npm init -y2. Install Dependencies
Install the necessary dependencies:
npm install express mongoose dotenv cors- express: Web framework for Node.js
- mongoose: ODM for MongoDB
- dotenv: Loads environment variables
- cors: Enables Cross-Origin Resource Sharing
For development purposes, install nodemon:
npm install --save-dev nodemonUpdate
package.jsonto include a start script:"scripts": { "start": "node server.js", "dev": "nodemon server.js" },3. Setting Up MongoDB
If you haven't set up MongoDB locally, you can use MongoDB Atlas for a free cloud database.
Create a
.envfile in thebackenddirectory:PORT=5000 MONGO_URI=your_mongodb_connection_stringReplace
your_mongodb_connection_stringwith your actual MongoDB connection string.4. Creating the Server with Express.js
Create
server.jsin thebackenddirectory:// server.js const express = require('express'); const mongoose = require('mongoose'); const dotenv = require('dotenv'); const cors = require('cors'); // Load environment variables dotenv.config(); const app = express(); // Middleware app.use(express.json()); app.use(cors()); // Connect to MongoDB mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log('MongoDB connected')) .catch((err) => console.log(err)); // Define Routes app.get('/', (req, res) => { res.send('Welcome to the Shoe Ordering API'); }); // Import route files const productRoutes = require('./routes/products'); const orderRoutes = require('./routes/orders'); // Use Routes app.use('/api/products', productRoutes); app.use('/api/orders', orderRoutes); // Start the server const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });5. Defining Models (Product & Order)
Create a
modelsdirectory insidebackend:mkdir modelsProduct Model
Create
Product.jsinsidemodels:// models/Product.js const mongoose = require('mongoose'); const ProductSchema = new mongoose.Schema({ name: { type: String, required: true }, description: String, price: { type: Number, required: true }, imageUrl: String, size: [Number], stock: { type: Number, default: 0 }, }, { timestamps: true }); module.exports = mongoose.model('Product', ProductSchema);Order Model
Create
Order.jsinsidemodels:// models/Order.js const mongoose = require('mongoose'); const OrderSchema = new mongoose.Schema({ products: [{ product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' }, quantity: { type: Number, default: 1 }, size: Number, }], total: { type: Number, required: true }, customerName: { type: String, required: true }, customerEmail: { type: String, required: true }, shippingAddress: { type: String, required: true }, }, { timestamps: true }); module.exports = mongoose.model('Order', OrderSchema);6. Creating API Routes
Create a
routesdirectory insidebackend:mkdir routesProduct Routes
Create
products.jsinsideroutes:// routes/products.js const express = require('express'); const router = express.Router(); const Product = require('../models/Product'); // GET all products router.get('/', async (req, res) => { try { const products = await Product.find(); res.json(products); } catch(err) { res.status(500).json({ message: err.message }); } }); // POST a new product router.post('/', async (req, res) => { const product = new Product({ name: req.body.name, description: req.body.description, price: req.body.price, imageUrl: req.body.imageUrl, size: req.body.size, stock: req.body.stock, }); try { const newProduct = await product.save(); res.status(201).json(newProduct); } catch(err) { res.status(400).json({ message: err.message }); } }); // GET a single product router.get('/:id', getProduct, (req, res) => { res.json(res.product); }); // UPDATE a product router.patch('/:id', getProduct, async (req, res) => { if (req.body.name != null) { res.product.name = req.body.name; } if (req.body.description != null) { res.product.description = req.body.description; } if (req.body.price != null) { res.product.price = req.body.price; } if (req.body.imageUrl != null) { res.product.imageUrl = req.body.imageUrl; } if (req.body.size != null) { res.product.size = req.body.size; } if (req.body.stock != null) { res.product.stock = req.body.stock; } try { const updatedProduct = await res.product.save(); res.json(updatedProduct); } catch(err) { res.status(400).json({ message: err.message }); } }); // DELETE a product router.delete('/:id', getProduct, async (req, res) => { try { await res.product.remove(); res.json({ message: 'Deleted Product' }); } catch(err) { res.status(500).json({ message: err.message }); } }); // Middleware to get product by ID async function getProduct(req, res, next) { let product; try { product = await Product.findById(req.params.id); if (product == null) { return res.status(404).json({ message: 'Cannot find product' }); } } catch(err) { return res.status(500).json({ message: err.message }); } res.product = product; next(); } module.exports = router;Order Routes
Create
orders.jsinsideroutes:// routes/orders.js const express = require('express'); const router = express.Router(); const Order = require('../models/Order'); const Product = require('../models/Product'); // GET all orders router.get('/', async (req, res) => { try { const orders = await Order.find().populate('products.product'); res.json(orders); } catch(err) { res.status(500).json({ message: err.message }); } }); // POST a new order router.post('/', async (req, res) => { const { products, total, customerName, customerEmail, shippingAddress } = req.body; // Validate products for (let item of products) { const product = await Product.findById(item.product); if (!product) { return res.status(400).json({ message: `Product not found: ${item.product}` }); } if (product.stock < item.quantity) { return res.status(400).json({ message: `Insufficient stock for product: ${product.name}` }); } } const order = new Order({ products, total, customerName, customerEmail, shippingAddress, }); try { const newOrder = await order.save(); // Update stock for (let item of products) { const product = await Product.findById(item.product); product.stock -= item.quantity; await product.save(); } res.status(201).json(newOrder); } catch(err) { res.status(400).json({ message: err.message }); } }); // GET a single order router.get('/:id', getOrder, (req, res) => { res.json(res.order); }); // Middleware to get order by ID async function getOrder(req, res, next) { let order; try { order = await Order.findById(req.params.id).populate('products.product'); if (order == null) { return res.status(404).json({ message: 'Cannot find order' }); } } catch(err) { return res.status(500).json({ message: err.message }); } res.order = order; next(); } module.exports = router;7. Testing the API
Start the server:
npm run devUse Postman or Insomnia to test the API endpoints:
- GET
http://localhost:5000/api/products- Get all products - POST
http://localhost:5000/api/products- Create a new product - GET
http://localhost:5000/api/products/:id- Get a product by ID - PATCH
http://localhost:5000/api/products/:id- Update a product - DELETE
http://localhost:5000/api/products/:id- Delete a product
Similarly, test order endpoints under
/api/orders.
Setting Up the Front End
1. Initialize the React Project
Navigate back to the root directory and create the
frontendfolder:cd .. npx create-react-app frontend cd frontend2. Install Dependencies
Install necessary dependencies:
npm install axios react-router-dom- axios: For making HTTP requests
- react-router-dom: For client-side routing
3. Creating Components
Create the following components inside
src/components:ProductList.jsProductDetail.jsCart.jsCheckout.jsNavbar.js
Navbar Component
Create a simple navigation bar.
// src/components/Navbar.js import React from 'react'; import { Link } from 'react-router-dom'; const Navbar = () => { return ( <nav style={styles.nav}> <h2><Link to="/" style={styles.link}>ShoeStore</Link></h2> <div> <Link to="/" style={styles.link}>Products</Link> <Link to="/cart" style={styles.link}>Cart</Link> </div> </nav> ); }; const styles = { nav: { display: 'flex', justifyContent: 'space-between', padding: '1rem', backgroundColor: '#333', color: '#fff', }, link: { color: '#fff', margin: '0 1rem', textDecoration: 'none', } }; export default Navbar;ProductList Component
Displays all products.
// src/components/ProductList.js import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { Link } from 'react-router-dom'; const ProductList = () => { const [products, setProducts] = useState([]); useEffect(() => { axios.get('http://localhost:5000/api/products') .then(response => { setProducts(response.data); }) .catch(error => console.log(error)); }, []); return ( <div style={styles.container}> {products.map(product => ( <div key={product._id} style={styles.card}> <img src={product.imageUrl} alt={product.name} style={styles.image} /> <h3>{product.name}</h3> <p>${product.price}</p> <Link to={`/products/${product._id}`}>View Details</Link> </div> ))} </div> ); }; const styles = { container: { display: 'flex', flexWrap: 'wrap', justifyContent: 'center', padding: '2rem', }, card: { border: '1px solid #ccc', borderRadius: '8px', padding: '1rem', margin: '1rem', width: '200px', textAlign: 'center', }, image: { width: '100%', height: '150px', objectFit: 'cover', } }; export default ProductList;ProductDetail Component
Displays detailed information about a product and allows adding to cart.
// src/components/ProductDetail.js import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { useParams } from 'react-router-dom'; const ProductDetail = () => { const { id } = useParams(); const [product, setProduct] = useState(null); const [size, setSize] = useState(''); const [quantity, setQuantity] = useState(1); useEffect(() => { axios.get(`http://localhost:5000/api/products/${id}`) .then(response => { setProduct(response.data); setSize(response.data.size[0]); }) .catch(error => console.log(error)); }, [id]); const addToCart = () => { const cart = JSON.parse(localStorage.getItem('cart')) || []; const existingItem = cart.find(item => item.id === product._id && item.size === size); if (existingItem) { existingItem.quantity += quantity; } else { cart.push({ id: product._id, name: product.name, price: product.price, size: size, quantity: quantity, imageUrl: product.imageUrl, }); } localStorage.setItem('cart', JSON.stringify(cart)); alert('Added to cart!'); }; if (!product) return <div>Loading...</div>; return ( <div style={styles.container}> <img src={product.imageUrl} alt={product.name} style={styles.image} /> <div style={styles.details}> <h2>{product.name}</h2> <p>{product.description}</p> <p><strong>Price:</strong> ${product.price}</p> <div> <label>Size: </label> <select value={size} onChange={(e) => setSize(e.target.value)}> {product.size.map(s => ( <option key={s} value={s}>{s}</option> ))} </select> </div> <div> <label>Quantity: </label> <input type="number" min="1" value={quantity} onChange={(e) => setQuantity(parseInt(e.target.value))} /> </div> <button onClick={addToCart} style={styles.button}>Add to Cart</button> </div> </div> ); }; const styles = { container: { display: 'flex', padding: '2rem', }, image: { width: '50%', height: 'auto', }, details: { marginLeft: '2rem', }, button: { padding: '0.5rem 1rem', backgroundColor: '#333', color: '#fff', border: 'none', cursor: 'pointer', marginTop: '1rem', } }; export default ProductDetail;Cart Component
Displays items in the cart and allows proceeding to checkout.
// src/components/Cart.js import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; const Cart = () => { const [cart, setCart] = useState([]); useEffect(() => { const cartItems = JSON.parse(localStorage.getItem('cart')) || []; setCart(cartItems); }, []); const removeFromCart = (index) => { const updatedCart = [...cart]; updatedCart.splice(index, 1); setCart(updatedCart); localStorage.setItem('cart', JSON.stringify(updatedCart)); }; const getTotal = () => { return cart.reduce((acc, item) => acc + item.price * item.quantity, 0); }; if (cart.length === 0) return <div style={styles.container}><h2>Your cart is empty</h2></div>; return ( <div style={styles.container}> <h2>Your Cart</h2> {cart.map((item, index) => ( <div key={index} style={styles.item}> <img src={item.imageUrl} alt={item.name} style={styles.image} /> <div> <h3>{item.name}</h3> <p>Size: {item.size}</p> <p>Quantity: {item.quantity}</p> <p>Price: ${item.price * item.quantity}</p> <button onClick={() => removeFromCart(index)} style={styles.button}>Remove</button> </div> </div> ))} <h3>Total: ${getTotal()}</h3> <Link to="/checkout"><button style={styles.checkoutButton}>Proceed to Checkout</button></Link> </div> ); }; const styles = { container: { padding: '2rem', }, item: { display: 'flex', marginBottom: '1rem', borderBottom: '1px solid #ccc', paddingBottom: '1rem', }, image: { width: '150px', height: '150px', objectFit: 'cover', marginRight: '1rem', }, button: { padding: '0.3rem 0.6rem', backgroundColor: '#c00', color: '#fff', border: 'none', cursor: 'pointer', }, checkoutButton: { padding: '0.7rem 1.5rem', backgroundColor: '#28a745', color: '#fff', border: 'none', cursor: 'pointer', marginTop: '1rem', } }; export default Cart;Checkout Component
Allows users to enter payment and shipping information.
// src/components/Checkout.js import React, { useState } from 'react'; import axios from 'axios'; const Checkout = () => { const [cart, setCart] = useState(JSON.parse(localStorage.getItem('cart')) || []); const [form, setForm] = useState({ customerName: '', customerEmail: '', shippingAddress: '', }); const handleChange = (e) => { setForm({...form, [e.target.name]: e.target.value}); }; const handleSubmit = (e) => { e.preventDefault(); if (cart.length === 0) { alert('Your cart is empty'); return; } const order = { products: cart.map(item => ({ product: item.id, quantity: item.quantity, size: item.size, })), total: cart.reduce((acc, item) => acc + item.price * item.quantity, 0), ...form, }; axios.post('http://localhost:5000/api/orders', order) .then(response => { alert('Order placed successfully!'); localStorage.removeItem('cart'); window.location.href = '/'; }) .catch(error => { console.log(error); alert('Error placing order. Please try again.'); }); }; return ( <div style={styles.container}> <h2>Checkout</h2> <form onSubmit={handleSubmit} style={styles.form}> <div style={styles.formGroup}> <label>Name:</label> <input type="text" name="customerName" value={form.customerName} onChange={handleChange} required /> </div> <div style={styles.formGroup}> <label>Email:</label> <input type="email" name="customerEmail" value={form.customerEmail} onChange={handleChange} required /> </div> <div style={styles.formGroup}> <label>Shipping Address:</label> <textarea name="shippingAddress" value={form.shippingAddress} onChange={handleChange} required /> </div> <button type="submit" style={styles.button}>Place Order</button> </form> </div> ); }; const styles = { container: { padding: '2rem', }, form: { display: 'flex', flexDirection: 'column', maxWidth: '400px', }, formGroup: { marginBottom: '1rem', }, button: { padding: '0.7rem', backgroundColor: '#007bff', color: '#fff', border: 'none', cursor: 'pointer', } }; export default Checkout;4. Setting Up Routing and App Component
Modify
App.jsto include routing.// src/App.js import React from 'react'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import Navbar from './components/Navbar'; import ProductList from './components/ProductList'; import ProductDetail from './components/ProductDetail'; import Cart from './components/Cart'; import Checkout from './components/Checkout'; function App() { return ( <Router> <Navbar /> <Routes> <Route path="/" element={<ProductList />} /> <Route path="/products/:id" element={<ProductDetail />} /> <Route path="/cart" element={<Cart />} /> <Route path="/checkout" element={<Checkout />} /> </Routes> </Router> ); } export default App;5. Styling the Application
The above components include inline styling for simplicity. For a production application, consider using CSS modules, Styled Components, or a CSS framework like Bootstrap or Material-UI for better scalability and maintainability.
6. Connecting to the Back End
Ensure that both the front end and back end are running concurrently. For development, you can handle CORS or set up a proxy.
Handling CORS
We've already included the
corsmiddleware in the back end, which allows cross-origin requests from the front end.Optional: Setting Up Proxy
Alternatively, you can set up a proxy in the React app to avoid specifying the full backend URL.
Add the following to
frontend/package.json:"proxy": "http://localhost:5000",Then, in your Axios requests, you can use relative paths like
/api/productsinstead ofhttp://localhost:5000/api/products.
Running the Application
-
Start the Back End
Open a terminal, navigate to the
backenddirectory, and run:npm run devThe server should start on
http://localhost:5000. -
Start the Front End
Open another terminal, navigate to the
frontenddirectory, and run:npm startThe React app should open in your default browser at
http://localhost:3000. -
Test the Application
- Visit
http://localhost:3000to see the product list. - Click on a product to view details and add it to the cart.
- Go to the cart to review items and proceed to checkout.
- Fill out the checkout form to place an order.
- Visit
-
Populate the Database
Initially, your MongoDB database will be empty. Use Postman or create an admin panel to add products to your store.
Example POST request to add a product:
POST http://localhost:5000/api/products Content-Type: application/json { "name": "Air Max 270", "description": "Comfortable running shoes", "price": 150, "imageUrl": "https://example.com/airmax270.jpg", "size": [7,8,9,10,11], "stock": 50 }
Deployment
To deploy your application, consider the following:
-
Back End Deployment
- Use platforms like Heroku, DigitalOcean, or AWS to host your Node.js server.
- Configure environment variables securely on the hosting platform.
- Use a managed database service or host MongoDB Atlas.
-
Front End Deployment
-
Domain and SSL
- Purchase a domain name and configure DNS settings.
- Ensure SSL certificates are set up for secure HTTP (HTTPS).
-
Environment Variables
- Never expose sensitive information like database credentials on the front end.
- Use environment variables and secure storage solutions.
Conclusion
This guide provides a foundational structure for building a full-stack shoe ordering website using the MERN stack. Depending on your requirements, you can expand this project by adding features such as:
- User Authentication: Allow users to create accounts and manage their orders.
- Admin Panel: Manage products, view orders, and handle inventory.
- Payment Integration: Integrate payment gateways like Stripe or PayPal.
- Responsive Design: Ensure the website works well on all devices.
- Enhanced UI/UX: Improve the visual appeal and user experience with advanced styling or UI libraries.
Building a complete e-commerce website involves many components and considerations, including security, performance, scalability, and user experience. Use this guide as a starting point and iteratively enhance your application based on best practices and user feedback.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.