Create a Node.js Express backend for a multi-vendor eCommerce platform. Implement RESTful APIs for managing Users (customer/vendor), Vendors, and Products. For Users: provide signup, login, and JWT-based authentication. For Vendors: allow vendor registration, profile management, and product upload. For Products: provide CRUD (Create, Read, Update, Delete) API endpoints. Store data in MongoDB using Mongoose models. Include proper middleware for authentication and role-based access control (Vendor vs Customer vs Admin). Each product should reference the Vendor who created it. - Follow Up Deployment
7f2c752 verified Download index.html from coolshano/frontend: direct link, hf CLI and curl.
- Browser
- Download file 27.8 kB
-
https://huggingface.co/spaces/coolshano/frontend/resolve/main/index.html
- Command line
-
hf download hf://spaces/coolshano/frontend/index.html
-
curl -L -o index.html https://huggingface.co/spaces/coolshano/frontend/resolve/main/index.html
27.8 kB
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Multi-Vendor eCommerce API Documentation</title> | |
| <script src="https://cdn.tailwindcss.com"></script> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> | |
| <style> | |
| .code-block { | |
| background-color: #1e293b; | |
| color: #f8fafc; | |
| padding: 1rem; | |
| border-radius: 0.5rem; | |
| font-family: monospace; | |
| overflow-x: auto; | |
| } | |
| .endpoint { | |
| border-left: 4px solid #3b82f6; | |
| padding-left: 1rem; | |
| margin-bottom: 2rem; | |
| } | |
| .method-get { color: #10b981; } | |
| .method-post { color: #f59e0b; } | |
| .method-put { color: #3b82f6; } | |
| .method-delete { color: #ef4444; } | |
| .tab-content { | |
| display: none; | |
| } | |
| .tab-content.active { | |
| display: block; | |
| } | |
| .nav-tabs .active { | |
| border-bottom: 2px solid #3b82f6; | |
| color: #3b82f6; | |
| } | |
| </style> | |
| </head> | |
| <body class="bg-gray-50"> | |
| <div class="container mx-auto px-4 py-8"> | |
| <header class="mb-12"> | |
| <h1 class="text-4xl font-bold text-gray-800 mb-2">Multi-Vendor eCommerce API</h1> | |
| <p class="text-xl text-gray-600">A complete Node.js Express backend for a multi-vendor eCommerce platform</p> | |
| </header> | |
| <div class="bg-white rounded-lg shadow-lg p-6 mb-8"> | |
| <h2 class="text-2xl font-semibold text-gray-800 mb-4">Features</h2> | |
| <div class="grid grid-cols-1 md:grid-cols-3 gap-4"> | |
| <div class="bg-blue-50 p-4 rounded-lg"> | |
| <div class="flex items-center mb-2"> | |
| <i class="fas fa-users text-blue-500 mr-2"></i> | |
| <h3 class="font-medium text-gray-800">User Management</h3> | |
| </div> | |
| <p class="text-gray-600">Signup, login, and JWT-based authentication for customers and vendors</p> | |
| </div> | |
| <div class="bg-green-50 p-4 rounded-lg"> | |
| <div class="flex items-center mb-2"> | |
| <i class="fas fa-store text-green-500 mr-2"></i> | |
| <h3 class="font-medium text-gray-800">Vendor System</h3> | |
| </div> | |
| <p class="text-gray-600">Vendor registration, profile management, and product upload</p> | |
| </div> | |
| <div class="bg-purple-50 p-4 rounded-lg"> | |
| <div class="flex items-center mb-2"> | |
| <i class="fas fa-boxes text-purple-500 mr-2"></i> | |
| <h3 class="font-medium text-gray-800">Product CRUD</h3> | |
| </div> | |
| <p class="text-gray-600">Complete product management with vendor references</p> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="flex mb-6 border-b"> | |
| <button class="nav-tabs px-4 py-2 font-medium active" data-tab="setup">Setup</button> | |
| <button class="nav-tabs px-4 py-2 font-medium" data-tab="models">Models</button> | |
| <button class="nav-tabs px-4 py-2 font-medium" data-tab="routes">Routes</button> | |
| <button class="nav-tabs px-4 py-2 font-medium" data-tab="middleware">Middleware</button> | |
| <button class="nav-tabs px-4 py-2 font-medium" data-tab="env">Environment</button> | |
| </div> | |
| <div id="setup" class="tab-content active"> | |
| <h2 class="text-2xl font-semibold text-gray-800 mb-4">Project Setup</h2> | |
| <div class="mb-6"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">1. Initialize Project</h3> | |
| <div class="code-block mb-4"> | |
| mkdir multi-vendor-ecommerce<br> | |
| cd multi-vendor-ecommerce<br> | |
| npm init -y<br> | |
| </div> | |
| </div> | |
| <div class="mb-6"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">2. Install Dependencies</h3> | |
| <div class="code-block mb-4"> | |
| npm install express mongoose bcryptjs jsonwebtoken express-validator dotenv cors multer | |
| </div> | |
| </div> | |
| <div class="mb-6"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">3. Project Structure</h3> | |
| <div class="code-block mb-4"> | |
| multi-vendor-ecommerce/<br> | |
| ├── config/ # Configuration files<br> | |
| │ └── db.js # Database connection<br> | |
| ├── controllers/ # Route controllers<br> | |
| │ ├── auth.js<br> | |
| │ ├── products.js<br> | |
| │ └── vendors.js<br> | |
| ├── middleware/ # Custom middleware<br> | |
| │ ├── auth.js<br> | |
| │ └── error.js<br> | |
| ├── models/ # Mongoose models<br> | |
| │ ├── Product.js<br> | |
| │ ├── User.js<br> | |
| │ └── Vendor.js<br> | |
| ├── routes/ # API routes<br> | |
| │ ├── auth.js<br> | |
| │ ├── products.js<br> | |
| │ └── vendors.js<br> | |
| ├── uploads/ # Product images<br> | |
| ├── utils/ # Utility functions<br> | |
| │ └── upload.js # File upload helper<br> | |
| ├── .env # Environment variables<br> | |
| └── server.js # Main application file<br> | |
| </div> | |
| </div> | |
| </div> | |
| <div id="models" class="tab-content"> | |
| <h2 class="text-2xl font-semibold text-gray-800 mb-4">Mongoose Models</h2> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">1. User Model (models/User.js)</h3> | |
| <div class="code-block mb-4"> | |
| const mongoose = require('mongoose'); | |
| const bcrypt = require('bcryptjs'); | |
| const jwt = require('jsonwebtoken'); | |
| const UserSchema = new mongoose.Schema({ | |
| name: { | |
| type: String, | |
| required: [true, 'Please add a name'] | |
| }, | |
| email: { | |
| type: String, | |
| required: [true, 'Please add an email'], | |
| unique: true, | |
| match: [ | |
| /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, | |
| 'Please add a valid email' | |
| ] | |
| }, | |
| role: { | |
| type: String, | |
| enum: ['customer', 'vendor', 'admin'], | |
| default: 'customer' | |
| }, | |
| password: { | |
| type: String, | |
| required: [true, 'Please add a password'], | |
| minlength: 6, | |
| select: false | |
| }, | |
| resetPasswordToken: String, | |
| resetPasswordExpire: Date, | |
| createdAt: { | |
| type: Date, | |
| default: Date.now | |
| } | |
| }); | |
| // Encrypt password using bcrypt | |
| UserSchema.pre('save', async function(next) { | |
| if (!this.isModified('password')) { | |
| next(); | |
| } | |
| const salt = await bcrypt.genSalt(10); | |
| this.password = await bcrypt.hash(this.password, salt); | |
| }); | |
| // Sign JWT and return | |
| UserSchema.methods.getSignedJwtToken = function() { | |
| return jwt.sign({ id: this._id }, process.env.JWT_SECRET, { | |
| expiresIn: process.env.JWT_EXPIRE | |
| }); | |
| }; | |
| // Match user entered password to hashed password in database | |
| UserSchema.methods.matchPassword = async function(enteredPassword) { | |
| return await bcrypt.compare(enteredPassword, this.password); | |
| }; | |
| module.exports = mongoose.model('User', UserSchema); | |
| </div> | |
| </div> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">2. Vendor Model (models/Vendor.js)</h3> | |
| <div class="code-block mb-4"> | |
| const mongoose = require('mongoose'); | |
| const VendorSchema = new mongoose.Schema({ | |
| user: { | |
| type: mongoose.Schema.ObjectId, | |
| ref: 'User', | |
| required: true, | |
| unique: true | |
| }, | |
| storeName: { | |
| type: String, | |
| required: [true, 'Please add a store name'], | |
| unique: true, | |
| trim: true, | |
| maxlength: [50, 'Store name cannot be more than 50 characters'] | |
| }, | |
| description: { | |
| type: String, | |
| required: [true, 'Please add a description'], | |
| maxlength: [500, 'Description cannot be more than 500 characters'] | |
| }, | |
| address: { | |
| type: String, | |
| required: [true, 'Please add an address'] | |
| }, | |
| phone: { | |
| type: String, | |
| required: [true, 'Please add a phone number'], | |
| maxlength: [20, 'Phone number cannot be longer than 20 characters'] | |
| }, | |
| website: { | |
| type: String, | |
| match: [ | |
| /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/, | |
| 'Please use a valid URL with HTTP or HTTPS' | |
| ] | |
| }, | |
| rating: { | |
| type: Number, | |
| min: [1, 'Rating must be at least 1'], | |
| max: [5, 'Rating must can not be more than 5'] | |
| }, | |
| createdAt: { | |
| type: Date, | |
| default: Date.now | |
| } | |
| }); | |
| module.exports = mongoose.model('Vendor', VendorSchema); | |
| </div> | |
| </div> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">3. Product Model (models/Product.js)</h3> | |
| <div class="code-block mb-4"> | |
| const mongoose = require('mongoose'); | |
| const ProductSchema = new mongoose.Schema({ | |
| name: { | |
| type: String, | |
| required: [true, 'Please add a product name'], | |
| trim: true, | |
| maxlength: [100, 'Product name cannot be more than 100 characters'] | |
| }, | |
| description: { | |
| type: String, | |
| required: [true, 'Please add a description'], | |
| maxlength: [1000, 'Description cannot be more than 1000 characters'] | |
| }, | |
| price: { | |
| type: Number, | |
| required: [true, 'Please add a price'], | |
| min: [0, 'Price must be at least 0'] | |
| }, | |
| category: { | |
| type: String, | |
| required: [true, 'Please add a category'], | |
| enum: [ | |
| 'Electronics', | |
| 'Clothing', | |
| 'Home', | |
| 'Books', | |
| 'Beauty', | |
| 'Sports', | |
| 'Other' | |
| ] | |
| }, | |
| stock: { | |
| type: Number, | |
| required: [true, 'Please add stock quantity'], | |
| min: [0, 'Stock cannot be less than 0'] | |
| }, | |
| images: { | |
| type: [String], | |
| default: [] | |
| }, | |
| vendor: { | |
| type: mongoose.Schema.ObjectId, | |
| ref: 'Vendor', | |
| required: true | |
| }, | |
| rating: { | |
| type: Number, | |
| min: [1, 'Rating must be at least 1'], | |
| max: [5, 'Rating must can not be more than 5'], | |
| default: 1 | |
| }, | |
| createdAt: { | |
| type: Date, | |
| default: Date.now | |
| } | |
| }); | |
| module.exports = mongoose.model('Product', ProductSchema); | |
| </div> | |
| </div> | |
| </div> | |
| <div id="routes" class="tab-content"> | |
| <h2 class="text-2xl font-semibold text-gray-800 mb-4">API Routes</h2> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-4">1. Authentication Routes (routes/auth.js)</h3> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-post font-bold mr-2">POST</span> | |
| <span class="text-gray-700">/api/v1/auth/register</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Register a new user (customer or vendor)</p> | |
| <div class="code-block mb-2"> | |
| // Request Body | |
| { | |
| "name": "John Doe", | |
| "email": "john@example.com", | |
| "password": "123456", | |
| "role": "customer" // or "vendor" | |
| } | |
| </div> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-post font-bold mr-2">POST</span> | |
| <span class="text-gray-700">/api/v1/auth/login</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Login user and get JWT token</p> | |
| <div class="code-block mb-2"> | |
| // Request Body | |
| { | |
| "email": "john@example.com", | |
| "password": "123456" | |
| } | |
| </div> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-get font-bold mr-2">GET</span> | |
| <span class="text-gray-700">/api/v1/auth/me</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Get currently logged in user (requires authentication)</p> | |
| </div> | |
| </div> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-4">2. Vendor Routes (routes/vendors.js)</h3> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-post font-bold mr-2">POST</span> | |
| <span class="text-gray-700">/api/v1/vendors</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Register as a vendor (requires user to be logged in)</p> | |
| <div class="code-block mb-2"> | |
| // Request Body | |
| { | |
| "storeName": "Awesome Store", | |
| "description": "We sell awesome products", | |
| "address": "123 Main St, City", | |
| "phone": "1234567890", | |
| "website": "https://awesomestore.com" | |
| } | |
| </div> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-get font-bold mr-2">GET</span> | |
| <span class="text-gray-700">/api/v1/vendors</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Get all vendors (public)</p> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-get font-bold mr-2">GET</span> | |
| <span class="text-gray-700">/api/v1/vendors/:id</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Get single vendor (public)</p> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-put font-bold mr-2">PUT</span> | |
| <span class="text-gray-700">/api/v1/vendors/:id</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Update vendor profile (requires vendor ownership or admin role)</p> | |
| </div> | |
| </div> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-4">3. Product Routes (routes/products.js)</h3> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-get font-bold mr-2">GET</span> | |
| <span class="text-gray-700">/api/v1/products</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Get all products (public, with filtering, pagination)</p> | |
| <div class="code-block mb-2"> | |
| // Query Parameters | |
| ?category=Electronics&price[lte]=1000&sort=-price&limit=10&page=1 | |
| </div> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-get font-bold mr-2">GET</span> | |
| <span class="text-gray-700">/api/v1/products/:id</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Get single product (public)</p> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-post font-bold mr-2">POST</span> | |
| <span class="text-gray-700">/api/v1/products</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Create new product (requires vendor role)</p> | |
| <div class="code-block mb-2"> | |
| // Request Body (multipart/form-data) | |
| { | |
| "name": "Smartphone", | |
| "description": "Latest smartphone", | |
| "price": 999.99, | |
| "category": "Electronics", | |
| "stock": 100, | |
| "images": [file1, file2] // Uploaded files | |
| } | |
| </div> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-put font-bold mr-2">PUT</span> | |
| <span class="text-gray-700">/api/v1/products/:id</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Update product (requires vendor ownership or admin role)</p> | |
| </div> | |
| <div class="endpoint mb-6"> | |
| <div class="flex items-center mb-2"> | |
| <span class="method-delete font-bold mr-2">DELETE</span> | |
| <span class="text-gray-700">/api/v1/products/:id</span> | |
| </div> | |
| <p class="text-gray-600 mb-2">Delete product (requires vendor ownership or admin role)</p> | |
| </div> | |
| </div> | |
| </div> | |
| <div id="middleware" class="tab-content"> | |
| <h2 class="text-2xl font-semibold text-gray-800 mb-4">Middleware</h2> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">1. Authentication Middleware (middleware/auth.js)</h3> | |
| <div class="code-block mb-4"> | |
| const jwt = require('jsonwebtoken'); | |
| const ErrorResponse = require('../utils/errorResponse'); | |
| const User = require('../models/User'); | |
| // Protect routes | |
| exports.protect = async (req, res, next) => { | |
| let token; | |
| if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) { | |
| token = req.headers.authorization.split(' ')[1]; | |
| } | |
| // Make sure token exists | |
| if (!token) { | |
| return next(new ErrorResponse('Not authorized to access this route', 401)); | |
| } | |
| try { | |
| // Verify token | |
| const decoded = jwt.verify(token, process.env.JWT_SECRET); | |
| req.user = await User.findById(decoded.id); | |
| next(); | |
| } catch (err) { | |
| return next(new ErrorResponse('Not authorized to access this route', 401)); | |
| } | |
| }; | |
| // Grant access to specific roles | |
| exports.authorize = (...roles) => { | |
| return (req, res, next) => { | |
| if (!roles.includes(req.user.role)) { | |
| return next( | |
| new ErrorResponse(`User role ${req.user.role} is not authorized to access this route`, 403) | |
| ); | |
| } | |
| next(); | |
| }; | |
| }; | |
| </div> | |
| </div> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">2. Error Handling Middleware (middleware/error.js)</h3> | |
| <div class="code-block mb-4"> | |
| const ErrorResponse = require('../utils/errorResponse'); | |
| const errorHandler = (err, req, res, next) => { | |
| let error = { ...err }; | |
| error.message = err.message; | |
| // Log to console for dev | |
| console.log(err); | |
| // Mongoose bad ObjectId | |
| if (err.name === 'CastError') { | |
| const message = `Resource not found with id of ${err.value}`; | |
| error = new ErrorResponse(message, 404); | |
| } | |
| // Mongoose duplicate key | |
| if (err.code === 11000) { | |
| const message = 'Duplicate field value entered'; | |
| error = new ErrorResponse(message, 400); | |
| } | |
| // Mongoose validation error | |
| if (err.name === 'ValidationError') { | |
| const message = Object.values(err.errors).map(val => val.message); | |
| error = new ErrorResponse(message, 400); | |
| } | |
| res.status(error.statusCode || 500).json({ | |
| success: false, | |
| error: error.message || 'Server Error' | |
| }); | |
| }; | |
| module.exports = errorHandler; | |
| </div> | |
| </div> | |
| <div class="mb-8"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">3. File Upload Middleware (utils/upload.js)</h3> | |
| <div class="code-block mb-4"> | |
| const multer = require('multer'); | |
| const path = require('path'); | |
| const fs = require('fs'); | |
| // Ensure uploads directory exists | |
| const uploadDir = path.join(__dirname, '../uploads'); | |
| if (!fs.existsSync(uploadDir)) { | |
| fs.mkdirSync(uploadDir, { recursive: true }); | |
| } | |
| // Set up storage for uploaded files | |
| const storage = multer.diskStorage({ | |
| destination: function(req, file, cb) { | |
| cb(null, uploadDir); | |
| }, | |
| filename: function(req, file, cb) { | |
| cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`); | |
| } | |
| }); | |
| // File filter for images only | |
| const fileFilter = (req, file, cb) => { | |
| const filetypes = /jpe?g|png|webp/; | |
| const mimetypes = /image\/jpe?g|image\/png|image\/webp/; | |
| const extname = filetypes.test(path.extname(file.originalname).toLowerCase()); | |
| const mimetype = mimetypes.test(file.mimetype); | |
| if (extname && mimetype) { | |
| cb(null, true); | |
| } else { | |
| cb(new Error('Images only!'), false); | |
| } | |
| }; | |
| const upload = multer({ | |
| storage, | |
| fileFilter, | |
| limits: { fileSize: 5 * 1024 * 1024 } // 5MB limit | |
| }); | |
| // Custom middleware for handling multiple image uploads | |
| exports.uploadProductImages = upload.array('images', 5); // Max 5 images | |
| // Middleware to process uploaded files | |
| exports.processImages = (req, res, next) => { | |
| if (!req.files || req.files.length === 0) { | |
| return next(); | |
| } | |
| req.body.images = req.files.map(file => `/uploads/${file.filename}`); | |
| next(); | |
| }; | |
| </div> | |
| </div> | |
| </div> | |
| <div id="env" class="tab-content"> | |
| <h2 class="text-2xl font-semibold text-gray-800 mb-4">Environment Configuration</h2> | |
| <div class="mb-6"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">.env File</h3> | |
| <div class="code-block mb-4"> | |
| NODE_ENV=development<br> | |
| PORT=5000<br> | |
| MONGO_URI=mongodb://localhost:27017/multi-vendor-ecommerce<br> | |
| JWT_SECRET=your_jwt_secret<br> | |
| JWT_EXPIRE=30d<br> | |
| JWT_COOKIE_EXPIRE=30<br> | |
| </div> | |
| </div> | |
| <div class="mb-6"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">Database Configuration (config/db.js)</h3> | |
| <div class="code-block mb-4"> | |
| const mongoose = require('mongoose'); | |
| const connectDB = async () => { | |
| try { | |
| const conn = await mongoose.connect(process.env.MONGO_URI, { | |
| useNewUrlParser: true, | |
| useCreateIndex: true, | |
| useFindAndModify: false, | |
| useUnifiedTopology: true | |
| }); | |
| console.log(`MongoDB Connected: ${conn.connection.host}`); | |
| } catch (err) { | |
| console.error(err); | |
| process.exit(1); | |
| } | |
| }; | |
| module.exports = connectDB; | |
| </div> | |
| </div> | |
| <div class="mb-6"> | |
| <h3 class="text-xl font-medium text-gray-800 mb-2">Main Server File (server.js)</h3> | |
| <div class="code-block mb-4"> | |
| const express = require('express'); | |
| const dotenv = require('dotenv'); | |
| const morgan = require('morgan'); | |
| const colors = require('colors'); | |
| const fileupload = require('express-fileupload'); | |
| const cookieParser = require('cookie-parser'); | |
| const mongoSanitize = require('express-mongo-sanitize'); | |
| const helmet = require('helmet'); | |
| const xss = require('xss-clean'); | |
| const rateLimit = require('express-rate-limit'); | |
| const hpp = require('hpp'); | |
| const cors = require('cors'); | |
| const errorHandler = require('./middleware/error'); | |
| const connectDB = require('./config/db'); | |
| // Load env vars | |
| dotenv.config({ path: './config/config.env' }); | |
| // Connect to database | |
| connectDB(); | |
| // Route files | |
| const auth = require('./routes/auth'); | |
| const vendors = require('./routes/vendors'); | |
| const products = require('./routes/products'); | |
| const app = express(); | |
| // Body parser | |
| app.use(express.json()); | |
| // Cookie parser | |
| app.use(cookieParser()); | |
| // Dev logging middleware | |
| if (process.env.NODE_ENV === 'development') { | |
| app.use(morgan('dev')); | |
| } | |
| // File uploading | |
| app.use(fileupload()); | |
| // Sanitize data | |
| app.use(mongoSanitize()); | |
| // Set security headers | |
| app.use(helmet()); | |
| // Prevent XSS attacks | |
| app.use(xss()); | |
| // Rate limiting | |
| const limiter = rateLimit({ | |
| windowMs: 10 * 60 * 1000, // 10 mins | |
| max: 100 | |
| }); | |
| app.use(limiter); | |
| // Prevent http param pollution | |
| app.use(hpp()); | |
| // Enable CORS | |
| app.use(cors()); | |
| // Set static folder | |
| app.use(express.static(path.join(__dirname, 'public'))); | |
| // Mount routers | |
| app.use('/api/v1/auth', auth); | |
| app.use('/api/v1/vendors', vendors); | |
| app.use('/api/v1/products', products); | |
| app.use(errorHandler); | |
| const PORT = process.env.PORT || 5000; | |
| const server = app.listen( | |
| PORT, | |
| console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold) | |
| ); | |
| // Handle unhandled promise rejections | |
| process.on('unhandledRejection', (err, promise) => { | |
| console.log(`Error: ${err.message}`.red); | |
| // Close server & exit process | |
| server.close(() => process.exit(1)); | |
| }); | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <script> | |
| // Tab functionality | |
| document.querySelectorAll('.nav-tabs').forEach(tab => { | |
| tab.addEventListener('click', () => { | |
| // Remove active class from all tabs and content | |
| document.querySelectorAll('.nav-tabs').forEach(t => t.classList.remove('active')); | |
| document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); | |
| // Add active class to clicked tab and corresponding content | |
| tab.classList.add('active'); | |
| const tabId = tab.getAttribute('data-tab'); | |
| document.getElementById(tabId).classList.add('active'); | |
| }); | |
| }); | |
| </script> | |
| <p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=coolshano/frontend" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body> | |
| </html> |