Share
Explore

Evolving the Men's Ware Emporium into a full Amazon.com Experience: Create a frontend Express.js web server to interact with our MongoDB backend.

image.png
info

Let's turn up the cognitive temperature and create a frontend Express.js web server to interact with our MongoDB backend.

We'll create forms for searching, displaying, and manipulating database records.

Integrating a Frontend Web Server for Men's Wear E-Commerce EmporiumClick to open document
This integration provides a comprehensive frontend solution that connects with our existing backend. Here's a summary of what we've added:
EJS templating engine for rendering dynamic HTML.
A layout template for consistent page structure.
Views for listing, showing, creating, and editing products (with instructions to create similar views for other entities).
Frontend routes that handle rendering views and processing form submissions.
Search functionality for products (which can be extended to other entities).
Bootstrap for basic styling and responsive design.
This setup allows students to:
View lists of products (and other entities)
Add new products through a web form
View details of individual products
Edit existing products
Delete products
Search for products by name
The workflow instructions provide a step-by-step guide for implementing and testing these features.
To keep the momentum going, you could challenge the students to:
Implement the views and routes for categories, customers, and orders.
Add more advanced search features (e.g., by price range, category, etc.).
Implement user authentication and restrict certain actions (like adding or deleting products) to authenticated users only.
Create a shopping cart system where customers can add products and create orders.
Implement a dashboard that shows key metrics (e.g., total sales, popular products).
These additions would further enhance their understanding of full-stack development and provide a more complete e-commerce experience.

Next steps:

Create a frontend Express.js web server to interact with our MongoDB backend.

We'll create forms for searching, displaying, and manipulating database records.


# Integrating a Frontend Web Server for Men's Wear E-Commerce Emporium

## Step 1: Set up EJS templating engine
1. Install EJS: ```bash npm install ejs ```
2. In your `server.js`, add: ```javascript app.set('view engine', 'ejs'); app.set('views', './views'); ```
## Step 2: Create Views
Create a `views` folder in your project root. We'll create the following EJS files:
1. `views/layout.ejs`: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Men's Wear E-Commerce Emporium</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="/">Men's Wear Emporium</a> <div class="navbar-nav"> <a class="nav-link" href="/products">Products</a> <a class="nav-link" href="/categories">Categories</a> <a class="nav-link" href="/customers">Customers</a> <a class="nav-link" href="/orders">Orders</a> </div> </div> </nav>
<div class="container mt-4"> <%- body %> </div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> </body> </html> ```
2. `views/products/index.ejs`, `views/products/show.ejs`, `views/products/new.ejs`, `views/products/edit.ejs` 3. Create similar files for categories, customers, and orders
## Step 3: Create Frontend Routes
Create a new file `routes/frontend.js`:
```javascript const express = require('express'); const router = express.Router(); const Product = require('../models/product'); const Category = require('../models/category'); const Customer = require('../models/customer'); const Order = require('../models/order');
// Products router.get('/products', async (req, res) => { const products = await Product.find().populate('category'); res.render('products/index', { products }); });
router.get('/products/new', async (req, res) => { const categories = await Category.find(); res.render('products/new', { categories }); });
router.post('/products', async (req, res) => { const product = new Product(req.body); await product.save(); res.redirect('/products'); });
router.get('/products/:id', async (req, res) => { const product = await Product.findById(req.params.id).populate('category'); res.render('products/show', { product }); });
router.get('/products/:id/edit', async (req, res) => { const product = await Product.findById(req.params.id); const categories = await Category.find(); res.render('products/edit', { product, categories }); });
router.post('/products/:id', async (req, res) => { await Product.findByIdAndUpdate(req.params.id, req.body); res.redirect('/products'); });
router.post('/products/:id/delete', async (req, res) => { await Product.findByIdAndDelete(req.params.id); res.redirect('/products'); });
// Add similar routes for categories, customers, and orders
module.exports = router; ```
## Step 4: Update server.js
Add the following to your `server.js`:
```javascript const expressLayouts = require('express-ejs-layouts'); const frontendRoutes = require('./routes/frontend');
app.use(expressLayouts); app.use(express.urlencoded({ extended: true })); app.use('/', frontendRoutes); ```
## Step 5: Implement Views
Here's an example for `views/products/index.ejs`:
```html <%- contentFor('body') %> <h1>Products</h1> <a href="/products/new" class="btn btn-primary mb-3">Add New Product</a> <table class="table"> <thead> <tr> <th>Name</th> <th>Price</th> <th>Category</th> <th>Actions</th> </tr> </thead> <tbody> <% products.forEach(product => { %> <tr> <td><%= product.name %></td> <td>$<%= product.price.toFixed(2) %></td> <td><%= product.category ? product.category.name : 'N/A' %></td> <td> <a href="/products/<%= product._id %>" class="btn btn-sm btn-info">View</a> <a href="/products/<%= product._id %>/edit" class="btn btn-sm btn-warning">Edit</a> <form action="/products/<%= product._id %>/delete" method="POST" class="d-inline"> <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</button> </form> </td> </tr> <% }) %> </tbody> </table> ```
Create similar views for other entities (categories, customers, orders).
## Step 6: Implement Search Functionality
Add a search form to `views/products/index.ejs`:
```html <form action="/products" method="GET" class="mb-3"> <div class="input-group"> <input type="text" name="search" class="form-control" placeholder="Search products..."> <button type="submit" class="btn btn-outline-secondary">Search</button> </div> </form> ```
Update the products route in `frontend.js`:
```javascript router.get('/products', async (req, res) => { let query = {}; if (req.query.search) { query = { name: { $regex: req.query.search, $options: 'i' } }; } const products = await Product.find(query).populate('category'); res.render('products/index', { products, search: req.query.search }); }); ```
## Workflow Instructions
1. Implement the layout and product views. 2. Create the frontend routes in `frontend.js`. 3. Update `server.js` to use the new frontend routes. 4. Test the product CRUD operations through the web interface. 5. Implement views and routes for categories, customers, and orders following the same pattern. 6. Add search functionality to other entity list views as needed. 7. Test all CRUD operations and search functionality for all entities.
This setup provides a basic but functional frontend for your Men's Wear E-Commerce Emporium. Students can now interact with the database through web forms, perform CRUD operations, and search for items.
To further challenge the students, consider adding: - User authentication and authorization - More advanced search and filtering options - A shopping cart functionality - An order processing workflow
This integration provides a comprehensive frontend solution that connects with our existing backend. Here's a summary of what we've added:
1. EJS templating engine for rendering dynamic HTML. 2. A layout template for consistent page structure. 3. Views for listing, showing, creating, and editing products (with instructions to create similar views for other entities). 4. Frontend routes that handle rendering views and processing form submissions. 5. Search functionality for products (which can be extended to other entities). 6. Bootstrap for basic styling and responsive design.
This setup allows students to: - View lists of products (and other entities) - Add new products through a web form - View details of individual products - Edit existing products - Delete products - Search for products by name
The workflow instructions provide a step-by-step guide for implementing and testing these features.
To keep the momentum going, you could challenge the students to: 1. Implement the views and routes for categories, customers, and orders. 2. Add more advanced search features (e.g., by price range, category, etc.). 3. Implement user authentication and restrict certain actions (like adding or deleting products) to authenticated users only. 4. Create a shopping cart system where customers can add products and create orders. 5. Implement a dashboard that shows key metrics (e.g., total sales, popular products).
These additions would further enhance their understanding of full-stack development and provide a more complete e-commerce experience.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.