0% found this document useful (0 votes)
39 views57 pages

Foodify

The document provides comprehensive documentation for a food delivery system named Foodify, built using the MERN stack. It includes sections on prerequisites, project structure, installation, deployment, features for both admin and customers, and API endpoints. The project aims to streamline food ordering and enhance customer satisfaction through a user-friendly interface and efficient backend management.

Uploaded by

tckillermano
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views57 pages

Foodify

The document provides comprehensive documentation for a food delivery system named Foodify, built using the MERN stack. It includes sections on prerequisites, project structure, installation, deployment, features for both admin and customers, and API endpoints. The project aims to streamline food ordering and enhance customer satisfaction through a user-friendly interface and efficient backend management.

Uploaded by

tckillermano
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

PROJECT

DOCUMENTATION

Dt:- 17/03/2025
Name:- Divakar T
Serial Number Table of ContentsPage Number

1. Introduction 3

2. Prerequisites 3

3. Project Structure 4

4. Installation 9

5. Deployment 10

6. Features 10

7. API Endpoints 11
8. Conclusion 42
9. Reference 43
10. Challenges 44

11. Features to add 45


12. Screenshots 47

2
Documentation for Food Delivery System using MERN Stack
Table of Contents
1. Introduction
2. Prerequisites
3. Project Structure
4. Installation
5. Deployment
6. Features
7. API Endpoints
8. Conclusion

1. Introduction:-
Foodify is a full-featured, responsive food delivery application built
using the MERN stack (MongoDB, Express, React, Node.js) with Stripe
payment integration. This project delivers a seamless experience for
customers, administrators, and delivery personnel, combining a user-
friendly frontend, a robust backend, and an intuitive admin panel into a
single, comprehensive platform.

2. Prerequisites:-
Before you begin, ensure you have the following installed:
 Node.js (version 14 or higher)
 MongoDB (local installation or MongoDB Atlas)
 npm
 Git (optional, for version control)

3
3. Project Structure:-
The project is structured as follows:
COLLEGE LIVE PROJECT/
Folder Structure for admin
├── Admin/
│ ├── assets/
│ ├── assets.js
│ ├── components/
│ │ ├── Navbar/
│ │ │ ├── Navbar.jsx
│ │ │ ├── Navbar.css
│ │ ├── Sidebar/
│ │ │ ├── Sidebar.jsx
│ │ │ ├── Sidebar.css
│ ├── pages/
│ │ │ ├── Add/
│ │ │ │ ├── Add.jsx
│ │ │ │ ├── Add.css
│ │ │ ├── List/
│ │ │ │ ├── List.jsx
│ │ │ │ ├── List.css
│ │ ├── Orders/
│ │ │ ├── Order.jsx
│ │ │ ├── Order.css
│ ├── App.js
│ ├── App.css

4
│ ├── index.html
Folder Structure for backend
├── Backend/
│ ├── config/
│ │ ├── db.js # Database configuration
│ ├── controllers/
│ │ ├── cartController.js # Logic for control cart
│ │ ├── foodController.js # Logic for control food
│ │ ├── orderController.js # Logic for placing orders
│ │ ├── userController.js # Logic for managing user accounts
│ ├── models/
│ │ ├── foodModel.js # Database model for food
│ │ ├── orderModel.js # Database model for orders restaurants
│ │ ├── userModel.js # Database model for user
│ ├── routes/
│ │ ├── cartRoute.js # API endpoints for cart
│ │ ├── foodRoute.js # API endpoints for food
│ │ ├── orderRoute.js # API endpoints for orders
│ │ ├── userRoute.js # API endpoints for user
│ ├── server.js # server connection
Folder Structure for frontend containing client-side logic
├── Frontend/
│ ├── public/
│ │ ├── favicon.icon
│ ├── src/
│ │ ├── components/
│ │ │ ├── AppDownload/
5
│ │ │ │ ├── AppDownload.jsx
│ │ │ │ ├── AppDownload.css
│ │ │ ├── ExploreMenu/
│ │ │ │ ├── ExploreMenu.jsx
│ │ │ │ ├── ExploreMenu.css
│ │ │ ├── FoodDisplay/
│ │ │ │ ├── FoodDisplay.jsx
│ │ │ │ ├── FoodDisplay.css
│ │ │ ├── FoodItem/
│ │ │ │ ├── FoodItem.jsx
│ │ │ │ ├── FoodItem.css
│ │ │ ├── Footer/
│ │ │ │ ├── Footer.jsx
│ │ │ │ ├── Footer.css
│ │ │ ├── Header/
│ │ │ │ ├── Header.jsx
│ │ │ │ ├── Header.css
│ │ │ ├── LoginPopup/
│ │ │ │ ├── LoginPopup.jsx
│ │ │ │ ├── LoginPopup.css
│ │ │ ├── Navbar/
│ │ │ │ ├── Navbar.jsx
│ │ │ │ ├── Navbar.css
│ │ │ ├── Context/
│ │ │ │ ├── StoreContext.js
│ │ ├── pages/
│ │ │ ├── Cart/
6
│ │ │ │ ├── Cart.jsx
│ │ │ │ ├── Cart.css
│ │ │ ├── Home/
│ │ │ │ ├── Home.jsx
│ │ │ │ ├── Home.css
│ │ │ ├── MyOrder/
│ │ │ │ ├── MyOrder.jsx
│ │ │ │ ├── MyOrder.css
│ │ │ ├── PlaceOrder/
│ │ │ │ ├── PlaceOrder.jsx
│ │ │ │ ├──PlaceOrder.css
│ │ │ ├── Verify/
│ │ │ │ ├── Verify.jsx
│ │ │ │ ├── Verify.css
│ │ ├── App.js

Admin Folder Structure


 assets/: Static assets such as images, fonts, and stylesheets.
 components/: Reusable UI components such as Navbar and Sidebar.
 pages/: Top-level pages such as Add, List, and Orders.
 App.js: Main application file.
 index.html: Entry point for the application.
Backend Folder Structure
 config/: Contains configuration files like database connection
settings.
 controllers/: business logic for handling API requests.
 models/: Contains database schema definitions using an ORM like
Mongoose.
7
 routes/: Defines API routes and maps them to controllers.
 node_modules/: Stores installed Node.js dependencies.
 app.js: Main server file where the Express application is initialized.
 .env: Stores environment variables such as API keys, database URIs,
etc.
 package.json: Contains project metadata and dependencies.
Frontend Folder Structure
 src/: Main source folder for the frontend.
o Pages/: Contains individual pages of the application, organized
by functionality.
o assets/: Stores all static assets, such as images and fonts.
o styles/: Contains global CSS and reusable styles for the
application.
o index.js: The entry point that renders the React application.
o App.js: The main component that wraps the entire application.
Root Files
 .gitignore: Specifies files and folders to ignore in Git.
 package.json: Holds project metadata and dependencies.
 README.md: Provides project documentation and setup
instructions.
Tests and Monitoring
 App.test.js: Contains test cases for the main App component.
 setupTests.js: Configures testing libraries.
 reportWebVitals.js: Measures app performance

4. Installation:-

Step 1: Clone the Repository


Clone the repository from GitHub or your version control system:

8
1)git clone https://github.com/your_username/e-learning-platform.git
2)cd e-learning-platform

Step 2: Install Backend Dependencies


Navigate to the server directory and install the necessary packages:
1)cd server
2)npm install

Step 3: Install Frontend Dependencies


Navigate to the client directory and install the necessary packages:
1)cd ../client
2)npm install

Step 4: Environment Variables


Create a .env file in the server directory to store environment variables.
Here’s a sample configuration:
copy
1)MONGO_URI=mongodb://localhost:5174/foodify
2)PORT=4000
3)JWT_SECRET=your_jwt_secret

5. Deployment:-
Backend Deployment
1. Choose a Hosting Service: You can use services like Heroku,
DigitalOcean, or AWS for deploying your backend.

9
2. Push Code: Use Git to push your code to the hosting service.
3. Set Environment Variables: Ensure that you set the environment
variables in your hosting service.
Frontend Deployment
1. Build the React Application:
1)cd client
2)npm run build
2. Deploy the Build Folder: You can use services like Netlify, Vercel,
or GitHub Pages to host the static files generated in the build folder.

6. Features:-
For Admin
 Add New Food: Admin can add new food into the list and delete from
the list.
 Check List: Admin can check all food lists.
 Check All Orders: Admin can check all food orders.
 Order Status: Admin can edit order status.
For Customer
 Sign Up and Login: customers can register and login into the app.
 View food: customer can view all food category wise
 Order food: customer can order any food he wants.
 Check Status: customer can check their order status.

7. API Endpoints:-

Cart Route
 GET /cart: Retrieve cart contents
 POST /cart: Add item to cart
 DELETE /cart: Clear cart

10
Food Route
 GET /foods: Retrieve list of available foods
 GET /foods/:id: Retrieve food details by ID
 POST /foods: Create new food item
 PUT /foods/:id: Update food item details
 DELETE /foods/:id: Delete food item
Order Route
 GET /orders: Retrieve list of orders
 POST /orders: Create new order
 PUT /orders/:id: Update order status
 DELETE /orders/:id: Cancel order
User Route
 GET /users: Retrieve list of users
 GET /users/:id: Retrieve user details by ID
 POST /users: Create new user
 PUT /users/:id: Update user details
 DELETE /users/:id: Delete user
Authentication Route
 POST /login: Login user
 POST /register: Register new user
 POST /logout: Logout user

9. Conclusion:-
It provides a simple way for customers to order food from a restaurant
using their device, allowing them to enjoy their food within 45 minutes. It
stores customer and food item details and generates bills to reduce time
wasting and avoid misunderstandings compared to traditional in-person
ordering. The system also allows users to easily modify their profile
information like delivery addresses. Overall, the project aims to provide

11
easy data flow, customer satisfaction, and less work through the developed
online platform.

FRONTEND
Frontend-Live-Project/
Node Modules
 node_modules/: Folder containing installed npm packages
Public: public/: Folder containing static assets accessible from the web
 index.html: Main HTML file for the application
 favicon.ico: Favicon for the application
 manifest.json: Web app manifest file
Source (Src): Folder containing application source code
 components/: Reusable UI components
 containers/: Components that wrap other components
 images/: Image assets
 styles/: CSS stylesheets
 App.js: Main application component
 index.js: Entry point for the application
Index
 index.html: Entry point for the application (served from public/ folder)
 index.js: Entry point for the application (served from src/ folder)
Package JSON: File containing project metadata and dependencies
Readme: File containing project information and setup instructions

NODE MODULES
To install the node_modules folder in your frontend project, you need to
install the project's dependencies listed in the package.json file using the
following command:
Command to Install Node Modules:-
npm install.

1. Basic Information
 name: The name of the project is "front". This could refer to a front-
end application or simply a naming convention used for the project.
 version: The version of the project is 0.1.0, indicating this is an early
version of the project.

12
 private: The project is marked as true for "private", meaning it
cannot be accidentally published to the npm registry.

2. Dependencies
These are the libraries and packages your project relies on to function.
Here are the dependencies and their purposes:
 axios: A promise-based HTTP client for making API requests.
 react: The React library itself (version 18.2.0), used for building the
UI of the app.
 react-dom: This package provides the DOM-related functions for
React (used with react to render components).
 react-router-dom: A library for routing in React applications,
allowing for page navigation without a page reload.
 react-toastify: A library for adding toast notifications to your React
app.
 web-vitals: A package for measuring and reporting on the core web
vitals (performance metrics) of a website.

3. Scripts
These are custom commands you can run using npm. These are commonly
used tasks during development and production deployment:
 start: Runs react-scripts start, which starts the development server,
typically at http://localhost:3000, with hot reloading enabled.
 build: Builds the project for production. The set
"GENERATE_SOURCEMAP=false" part ensures that the source maps
are not generated (which can help reduce build size).
 test: Runs tests using react-scripts test. This runs the testing
framework (Jest) and looks for test files in the project.
 eject: Ejects the configuration from create-react-app. This gives you
full control over the configuration files (webpack, Babel, ESLint, etc.),
but it is not reversible.

4. ESLint Configuration
 eslintConfig: Specifies the ESLint configuration for the project:

13
o extends: This section includes base configurations for ESLint. It
extends react-app for general React rules and react-app/jest for
Jest testing rules.
o ESLint is a tool for identifying and fixing JavaScript code quality
and style issues.

5. Browserslist
 browserslist: Specifies the list of supported browsers for both
production and development environments.
o production: This configuration tells tools (e.g., Babel,
Autoprefixer) to support browsers with more than 0.2% market
share, excluding "dead" browsers and "Opera Mini."
o development: In the development environment, it supports the
last version of Chrome, Firefox, and Safari browsers. This is
useful for minimizing the browser range to improve build
performance in development.

Summary:
 The project is a React application using Create React App (react-
scripts).
 It includes popular libraries for testing (@testing-library/react), UI
(bootstrap, react-toastify), and making HTTP requests (axios).
 The scripts section defines commands for starting, building, testing,
and ejecting the app.
 The eslintConfig and browserslist help with code quality and browser
compatibility respectively.
Install axios:
Run the following command to install:-
npm install axios

Verify Installation:
Once installation is complete, check the node_modules folder to ensure
axios is installed. You can also confirm it by looking at the package.json file
under the "dependencies" section:

"dependencies": {

14
"axios": "^1.7.9"
}
Use axios in your project:

After installing axios, you can import and use it in your React project like
this:

import axios from 'axios';


// Example usage:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});

1. src/
The src folder contains the main source code for the React application. All
the components, assets, and logic reside here.
Pages/
This folder likely holds individual React components or pages for routing
purposes. For example, pages like Home.js, About.js, or Dashboard.js
might reside here. It organizes the structure of the app by separating page-
specific components.
App.css
This file contains the CSS styles specific to the App.js component. It helps
in maintaining the styling of the main app layout.
App.js
The main React component that serves as the root of the application. It
renders the primary structure of the app, usually containing the routes or
other major components.
App.test.js
A testing file created by default in React apps (if testing is enabled). It
typically uses the Jest testing library to validate the functionality of the
App.js component.
index.css

15
Global CSS styles for the entire application. It is usually imported in
index.js to apply the styles across the app.
index.js
The entry point of the React app. It renders the App.js component into the
root DOM element (<div id="root"> in index.html). This file is critical for
bootstrapping the React app.
logo.svg
A default logo file included in React apps. It's usually displayed in the
initial boilerplate project and can be replaced with a custom logo.

reportWebVitals.js
A utility file for measuring and logging app performance metrics (e.g., page
load time). It can be used to send performance data to analytics services.

setupTests.js
This file configures the testing environment for the app. It’s automatically
included when using create-react-app with a testing setup like Jest.

2. Project Root Files


These files are located in the root of the project folder, outside of src.

.gitignore
This file specifies files and directories that should be ignored by Git. For
example, node_modules, build outputs, and environment files are
commonly listed here.

package-lock.json
This file locks the exact versions of all installed dependencies. It ensures
consistent builds across different environments.

package.json
A crucial file in a Node.js project. It defines the project metadata,
dependencies, and scripts. Key fields include:
 dependencies: Libraries required for the app to run.
 scripts: Commands to build, test, or run the app (e.g., npm start).

16
README.md
A markdown file that usually contains information about the project. It may
include setup instructions, usage details, and other relevant
documentation.

vercel.json
This configuration file is specific to deploying the app on Vercel. It defines
deployment settings such as routes, rewrites, or build instructions.

17
NODE MODULES
The node_modules folder in a frontend project contains all the
dependencies (libraries and modules) required for the application to run,
build, and function correctly. These dependencies are installed using npm
(Node Package Manager) and are listed in the package.json file. Here's an
explanation of common types of node_modules used in frontend projects:
The node_modules folder in a frontend project contains all the
dependencies (libraries and modules) required for the application to run,
build, and function correctly. These dependencies are installed using npm
(Node Package Manager) and are listed in the package.json file. Here's an
explanation of common types of node_modules used in frontend projects:

1. Framework/Library Modules
 react: Core React library for building UI components.
 react-dom: Provides DOM-specific methods that allow React
components to be rendered in the browser.
 react-router-dom: Used for routing in a React application.
 redux/@reduxjs/toolkit: State management libraries for React
applications (if used).
 axios: Library for making HTTP requests from the frontend to a
backend API.
 firebase: Used for Firebase services, such as authentication,
database, or storage.

2. Build Tools
 webpack: A module bundler used to compile JavaScript, CSS, and
other assets into a single file.
 babel: A JavaScript compiler used to transform modern JavaScript
(ES6+) into a version compatible with older browsers.
 esbuild/swc: Modern alternatives to Babel and Webpack for faster
builds.

3. Styling Modules
 bootstrap: CSS framework for building responsive designs.
 tailwindcss: Utility-first CSS framework for styling components.

18
 sass or node-sass: Preprocessor for writing modular and nested
CSS.

4. Testing Libraries
 jest: A testing framework commonly used for JavaScript and React
projects.
 @testing-library/react: Helps test React components by simulating
user interactions.

19
 @testing-library/jest-dom: Provides custom matchers for asserting
DOM nodes.

5. Utility Libraries
 lodash: Utility library for manipulating objects, arrays, and strings.
 moment/dayjs: Libraries for handling and formatting dates and
times.
 uuid: Generates unique IDs for React keys or other unique elements.

6. Development Dependencies
These modules are installed as devDependencies and are used only during
development.
 eslint: Linter for identifying and fixing coding issues.
 prettier: Code formatter for maintaining consistent style.
 react-scripts: A utility provided by Create React App to simplify
configuration for building, testing, and running a React app.
 webpack-dev-server: Provides a live development server for real-
time code updates.

7. Deployment/Build Modules
 vercel: For deploying apps on the Vercel platform.
 dotenv: For managing environment variables (e.g., API keys) in
development and production.
 workbox-webpack-plugin: Helps with building Progressive Web
Apps (PWAs).
How node_modules Are Managed:
 Dependencies and their versions are listed in the package.json file.

20
 Installed by running npm install or yarn install.
 Important: The node_modules folder should not be modified
manually or included in version control (e.g., Git). Instead, it is
regenerated using package.json and package-lock.json.

Common Issues with node_modules:


1. Missing or Corrupted Modules:
o Fix by running:
bash
Copy code
rm -rf node_modules package-lock.json
npm install
2. Large Folder Size:
o The node_modules folder can become very large because of
nested dependencies. This is normal for frontend projects.
3. Compatibility Issues:
o Use npm audit to check for vulnerabilities and fix outdated
packages.

Frontend folder image

BACKEND
Project Name: BACKEND-LIVE-PROJECT
This indicates that the project is a live backend application, likely
developed using Node.js with Express.js for creating APIs.

2. Folders
Backend/
This is the main folder for the backend portion of the application. It
contains all the configuration files, models, routes, and other essential
components required for the backend.

21
config/
This folder is typically used for configuration files, such as:
Database connection files (e.g., MongoDB, MySQL, etc.).
Environment-specific settings (e.g., development, production).

Example:-
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, { useNewUrlParser:
true, useUnifiedTopology: true });
console.log('MongoDB Connected');
} catch (error) {
console.error('Database Connection Failed', error);
process.exit(1);
}
};
module.exports = connectDB;

1. Project Name: BACKEND-LIVE-PROJECT


This indicates that the project is a live backend application, likely
developed using Node.js with Express.js for creating APIs.

2. Folders
Backend/
This is the main folder for the backend portion of the application. It
contains all the configuration files, models, routes, and other essential
components required for the backend.
config/
This folder is typically used for configuration files, such as:
 Database connection files (e.g., MongoDB, MySQL, etc.).
 Environment-specific settings (e.g., development, production).
 Example:
const mongoose = require('mongoose');
const connectDB = async () => {

22
try {
await mongoose.connect(process.env.MONGO_URI,
{ useNewUrlParser: true, useUnifiedTopology: true });
console.log('MongoDB Connected');
} catch (error) {
console.error('Database Connection Failed', error);
process.exit(1);
}
};

module.exports = connectDB;

models/
This folder contains data models or schemas for the database. These
models define the structure of the data stored in the database.
Examples of the models inside this folder:
 foodModel.js: Defines the structure and schema for food items.
 orderModel.js: Defines the structure and schema for customer orders.
 userModel.js: Defines the structure and schema for user accounts,
including customers, restaurants, and administrators.
node_modules/
This folder contains all the dependencies and packages installed via
npm (Node Package Manager). These packages are defined in the
package.json file. Examples:
 Express.js for handling HTTP requests.
 Mongoose for MongoDB integration.
 dotenv for managing environment variables.

routes/
This folder contains the API routes of the application. Each file
corresponds to a specific feature/module and contains endpoints for CRUD
operations.

23
 cartRoute.js: Handles cart-related operations, such as adding,
removing, and updating items.
 foodRoute.js: Handles food-related operations, such as retrieving food
items, creating new items, and updating existing ones.
 orderRoute.js: Handles order-related operations, such as creating new
orders, retrieving order history, and updating order status.
 userRoute.js: Handles user-related operations, such as user
registration, login, and account management.
Example of a route (using Express):
import express from 'express';
import { addFood, listFood, removeFood } from
'../controllers/foodController.js';
import multer from 'multer';
const foodRouter = express.Router();

//Image Storage Engine (Saving Image to uploads folder & rename it)

const storage = multer.diskStorage({


destination: 'uploads',
filename: (req, file, cb) => {
return cb(null,`${Date.now()}${file.originalname}`);
}
})

const upload = multer({ storage: storage})

foodRouter.get("/list",listFood);
foodRouter.post("/add",upload.single('image'),addFood);
foodRouter.post("/remove",removeFood);

export default foodRouter;

24
3. Files
.env
This file stores environment variables that are used throughout the
project. These variables are kept secret (e.g., database credentials, API
keys).
Example:
PORT=4000
MONGO_URI=mongodb://localhost:2174/MyDatabase
JWT_SECRET=mysecretkey
.gitignore
Specifies files and folders to be ignored by Git. Commonly ignored
items include:
 node_modules/
 .env
 logs/
 Example content:
node_modules/
.env
logs/
app.js
The main entry point for the backend application. It initializes the
server, middleware, and routes.
Example content:
// app config
const app = express()
const port = process.env.PORT || 4000;

// middlewares
app.use(express.json())
app.use(cors())

// db connection
connectDB()

// api endpoints
app.use("/api/user", userRouter)
25
app.use("/api/food", foodRouter)
app.use("/images",express.static('uploads'))
app.use("/api/cart", cartRouter)
app.use("/api/order",orderRouter)

app.get("/", (req, res) => {


res.send("API Working")
});

app.listen(port, () => console.log(`Server started on http://localhost:$


{port}`))

package.json
A configuration file for the Node.js project. It lists:
 Project metadata (name, version, description).
 Dependencies (packages required for the project).
 Scripts for running commands.

Example content:
json

26
{
"name": "food-del-backend",
"version": "1.0.0",
"type": "module",
"main": "server.js",
"scripts": {
"server": "nodemon server.js",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.1",
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.9.5",
"multer": "^1.4.5-lts.1",
"nodemon": "^3.1.9",
"stripe": "^14.25.0",
"validator": "^13.12.0"
},
"keywords": [],
"description": ""
}

This file locks the versions of all installed dependencies to ensure


consistency across different environments.

1. These files are models used to interact with a database, often in a


CRUD application:
o Create: Add new records to the database.
o Read: Fetch records (e.g., courses, students, news).
o Update: Modify existing records.

27
o Delete: Remove records.
2. These models are imported into routes or controllers to define APIs or
application logic.

Backend folder image

28
Key Components of the Router in the Backend
1. Routing Framework/Library:
o Most modern backend frameworks (like Express.js in Node.js)
include a router feature that allows you to define routes easily.
2. Defining Routes:
o A route maps an HTTP method (e.g., GET, POST, PUT,
DELETE) and a URL path to a handler function.

3. Routing Middleware:
o Middleware functions can process requests before they reach
the route handler. Middleware can:
 Authenticate requests.
 Parse incoming data (e.g., JSON payloads).
 Log requests.
4. Dynamic and Parameterized Routes:
o Routes can include dynamic segments to handle multiple similar
endpoints.
javascript
5. Modular Routing:
o For better structure and maintainability, routes can be split into
multiple files/modules.
javascript
Copy code
6. Route Handlers:
o A route handler is a function that executes the business logic
when a specific route is accessed.

How Router Fits in the Backend Architecture


The router is part of the request-handling pipeline:

1. Request: A client sends an HTTP request to the server (e.g., GET


/api/users).
2. Routing: The server matches the request's path and method to a
route defined in the router.

29
3. Middleware: Middleware functions are executed (e.g.,
authentication, data parsing).
4. Handler: The route's handler function processes the request and
sends a response.
5. Response: The server sends back an HTTP response to the client.

ADMIN PANEL
AddFood.jsx
import axios from 'axios';
import React, { useState } from 'react';
import { toast } from 'react-toastify';
import { assets } from '../../assets/assets';
import './Add.css';

const Add = () => {

// const url="http://localhost:4000"
const url = "https://food-delivery-backend-au4q.onrender.com"
const [data, setData] = useState({
name: "",
description: "",
price: "",
category: "Cake"
});

const [image, setImage] = useState(false);

const onSubmitHandler = async (event) => {


event.preventDefault();
const formData = new FormData();
formData.append("name", data.name);
formData.append("description", data.description);
formData.append("price", Number(data.price));
formData.append("category", data.category);
30
formData.append("image", image);
const response = await axios.post(`${url}/api/food/add`, formData);
if (response.data.success) {
toast.success(response.data.message)
setData({
name: "",
description: "",
price: "",
category: "Cake"
})
setImage(false);
}
else{
toast.error(response.data.message)
}
}

const onChangeHandler = (event) => {


const name = event.target.name;
const value = event.target.value;
setData(data => ({ ...data, [name]: value }))
}

return (
<div className='add'>
<form className='flex-col' onSubmit={onSubmitHandler}>
<div className='add-img-upload flex-col'>
<p>Upload image</p>
<label htmlFor="image">
<img src={!image ? assets.upload_area :
URL.createObjectURL(image)} alt="" />
</label>
<input onChange={(e) => { setImage(e.target.files[0]) }}
type="file" id="image" hidden required />
</div>
<div className='add-product-name flex-col'>

31
<p>Product name</p>
<input name='name' onChange={onChangeHandler}
value={data.name} type="text" placeholder='Type here' required />
</div>
<div className='add-product-description flex-col'>
<p>Product description</p>
<textarea name='description' onChange={onChangeHandler}
value={data.description} type="text" rows={6} placeholder='Write
content here' required />
</div>
<div className='add-category-price'>
<div className='add-category flex-col'>
<p>Product category</p>
<select name='category' onChange={onChangeHandler} >
<option value="Cake">Cake</option>
<option value="Fish">Fish</option>
<option value="Chicken">Chicken</option>
<option value="Mutton">Mutton</option>
<option value="Pure Veg">Pure Veg</option>
<option value="Rolls">Rolls</option>
</select>
</div>
<div className='add-price flex-col'>
<p>Product Price</p>
<input type="Number" name='price'
onChange={onChangeHandler} value={data.price} placeholder='$25' />
</div>
</div>
<button type='submit' className='add-btn' >ADD</button>
</form>
</div>
)
}

export default Add

32
Order.jsx

import React, { useEffect, useState } from 'react'


import './Orders.css'
import { toast } from 'react-toastify';
import axios from 'axios';
import { assets, url } from '../../assets/assets';

const Order = () => {

const [orders, setOrders] = useState([]);

const fetchAllOrders = async () => {


const response = await axios.get(`${url}/api/order/list`)
if (response.data.success) {
setOrders(response.data.data.reverse());
console.log(response.data.data);
}
else {
toast.error("Error")
}
}

const statusHandler = async (event,orderId) => {


console.log(event,orderId);
const response = await axios.post(`${url}/api/order/status`,{
orderId,
status:event.target.value
})
if(response.data.success)
{
await fetchAllOrders();
}
}

useEffect(() => {

33
fetchAllOrders();
}, [])

return (
<div className='order add'>
<h3>Order Page</h3>
<div className="order-list">
{orders.map((order, index) => (
<div key={index} className='order-item'>
<img src={assets.parcel_icon} alt="" />
<div>
<p className='order-item-food'>
{order.items.map((item, index) => {
if (index === order.items.length - 1) {
return item.name + " x " + item.quantity
}
else {
return item.name + " x " + item.quantity + ", "
}
})}
</p>
<p className='order-item-name'>{order.address.firstName+"
"+order.address.lastName}</p>
<div className='order-item-address'>
<p>{order.address.street+","}</p>
<p>{order.address.city+", "+order.address.state+",
"+order.address.country+", "+order.address.zipcode}</p>
</div>
<p className='order-item-phone'>{order.address.phone}</p>
</div>
<p>Items : {order.items.length}</p>
<p>${order.amount}</p>
<select onChange={(e)=>statusHandler(e,order._id)}
value={order.status} name="" id="">
<option value="Food Processing">Food Processing</option>
<option value="Out for delivery">Out for delivery</option>

34
<option value="Delivered">Delivered</option>
</select>
</div>
))}
</div>
</div>
)
}

export default Order

List.jsx

import axios from 'axios';


import React, { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { url } from '../../assets/assets';
import './List.css';

const List = () => {

const [list,setList] = useState([]);

const fetchList = async () => {


const response = await axios.get(`${url}/api/food/list`)
if(response.data.success)
{
setList(response.data.data);
}
else{
toast.error("Error")
}
}

const removeFood = async (foodId) => {


const response = await axios.post(`${url}/api/food/remove`,{

35
id:foodId
})
await fetchList();
if (response.data.success) {
toast.success(response.data.message);
}
else {
toast.error("Error")
}
}

useEffect(()=>{
fetchList();
},[])

return (
<div className='list add flex-col'>
<p>All Foods List</p>
<div className='list-table'>
<div className="list-table-format title">
<b>Image</b>
<b>Name</b>
<b>Category</b>
<b>Price</b>
<b>Action</b>
</div>
{list.map((item,index)=>{
return (
<div key={index} className='list-table-format'>
<img src={`${url}/images/`+item.image} alt="" />
<p>{item.name}</p>
<p>{item.category}</p>
<p>${item.price}</p>
<p className='cursor'
onClick={()=>removeFood(item._id)}>x</p>
</div>

36
)
})}
</div>
</div>
)
}

export default List

Admin folder image

DEPLOYMENT
DEPLOYMENT OF FRONTEND PROJECT
Backend Deployment
1. Prepare Your Backend Project

37
1. Ensure all dependencies are correctly listed in the package.json
file.
2. Specify the start script:
o Add a start script in your package.json:
json
"scripts": {
"start": "node server.js"
}
Replace server.js with the entry file for your backend application.
3. Environment Variables:
o Ensure your application supports environment variables for
secrets like database credentials.
o Example:

const PORT = process.env.PORT || 4000;


app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

2. Push Your Code to Git


 Commit and push your backend code to a Git repository (GitHub,
GitLab, or Bitbucket).

3. Deploy on Render
1. Create a New Service:
o Log in to Render.com and click "New +" > "Web Service".
2. Connect Your Repository:
o Select the repository where your backend project is hosted.
3. Configure Service Settings:
o Name: Give your service a name (e.g., backend-service).
o Environment: Choose Node (or the appropriate environment).
o Build Command: Use npm install (or yarn install if using Yarn).
o Start Command: Use npm start (or the equivalent for your
project).
4. Add Environment Variables:
o Add any required variables (e.g., DB_URL, JWT_SECRET) under
the Environment section.
5. Choose Plan:

38
o Select the free tier or a paid plan depending on your needs.
6. Deploy:
o Click "Create Web Service" to start deployment.

4. Verify Deployment
 After deployment, Render provides a public URL for your backend
(e.g., https://backend-service.onrender.com).
 Test the endpoints using tools like Postman or curl.

39
FRONTEND PROJECT
Frontend Deployment
1. Prepare Your Frontend Project
1. Ensure your frontend is production-ready:
o Run the build command:
npm run build
o This will generate a build/ folder with optimized static files.
2. Verify the Build:
o Check that the build/ folder contains all the necessary files.

2. Push Your Code to Git


 Commit and push your frontend code to a Git repository (GitHub,
GitLab, or Bitbucket).

3. Deploy on Render
1. Create a New Service:
o Log in to Render.com and click "New +" > "Static Site".
2. Connect Your Repository:
o Select the repository where your frontend project is hosted.
3. Configure Service Settings:
o Name: Give your service a name (e.g., frontend-service).
o Build Command: Use npm run build (or the equivalent for your
project).
o Publish Directory: Set to build (or the directory containing your
production files).
4. Choose Plan:
o Select the free tier or a paid plan depending on your needs.
5. Deploy:
o Click "Create Static Site" to start deployment.

4. Verify Deployment
 After deployment, Render provides a public URL for your frontend
(e.g., https://frontend-service.onrender.com).
 Access this URL to verify your frontend is live.

40
Connect Frontend with Backend
1. Update your frontend code to use the backend's Render URL for API
calls:
o Example:
const API_URL = "https://backend-service.onrender.com";
fetch(`${API_URL}/endpoint`)
.then(response => response.json())
.then(data => console.log(data));

41
1. Install Postman
1. Download Postman:
o Go to the Postman website and download the application for your
operating system.
2. Install and Open Postman:
o Follow the installation steps and launch the app.

2. Understand the Basics


 Request Types: Common request methods include:
o GET: Retrieve data from the server.
o POST: Send data to the server.
o PUT: Update existing data on the server.
o DELETE: Remove data from the server.
 Headers: Used to send additional information like authentication
tokens or content type.
 Body: Contains the data to send (used in POST or PUT requests).
 Environment Variables: Store reusable variables like API URLs or
tokens.

3. Create a Request
1. Launch Postman and click "New" > "Request".
2. Name the Request (e.g., "User Login") and add it to a collection or
folder for organization.

4. Send a GET Request


1. Enter the Endpoint:
o Example: https://api.example.com/users
2. Select the HTTP Method:
o Choose GET from the dropdown next to the URL field.
3. Click "Send":

42
o Postman will send the request and display the server's response
in the lower pane.
4. Inspect the Response:
o Check the status code, response time, and body.

5. Send a POST Request


1. Enter the Endpoint:
o Example: https://api.example.com/users/login
2. Select POST Method:
o Choose POST from the dropdown.
3. Add Headers (if required):
o Example:
 Content-Type: application/json
o Go to the Headers tab and add key-value pairs.
4. Add Request Body:
o Go to the Body tab and select raw.
o Choose JSON format and enter the request payload:
json

{
"email": "[email protected]",
"password": "123456"
}
5. Click "Send":
o Postman sends the data to the server, and the response appears
in the lower pane.

6. Send a PUT Request


1. Enter the Endpoint:
o Example: https://api.example.com/users/123
2. Select PUT Method.
3. Add Headers:
o Example:
 Content-Type: application/json
4. Add Request Body:
o Go to the Body tab, select raw, and enter the updated data:

43
json

{
"name": "John Doe",
"email": "[email protected]"
}
5. Click "Send":
o View the updated response.

7. Send a DELETE Request


1. Enter the Endpoint:
o Example: https://api.example.com/users/123
2. Select DELETE Method.
3. Click "Send":
o Confirm deletion by inspecting the response.

8. Authentication in Postman
1. Go to the "Authorization" Tab:
o Select the appropriate type (e.g., Bearer Token, Basic Auth).
2. Enter Credentials or Token:
o Example: For Bearer Token, add:
makefile
CopyEdit
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

9. Save Requests in Collections


1. Organize related requests into Collections for easier management.
2. Save requests by clicking Save after sending them.

10. Use Environment Variables


1. Define Variables:
o Example: Create a variable for BASE_URL as
https://api.example.com.
2. Use Variables in Requests:
o Replace the endpoint with {{BASE_URL}}/users.
3. Set Environments:
44
o Switch between different environments like Development or
Production.

11. Testing and Validation


1. Write Tests:
o Add JavaScript-based tests under the Tests tab:
javascript
CopyEdit
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
2. Automate Tests:
o Run multiple requests from a collection and validate responses.

12. Debugging
1. Check for errors in the response.
2. Use the Console (View > Show Postman Console) to inspect log

Conclusion:
It provides a simple way for customers to order food from a restaurant
using their device, allowing them to enjoy their food within 45 minutes. It
stores customer and food item details and generates bills to reduce time
wasting and avoid misunderstandings compared to traditional in-person
ordering. The system also allows users to easily modify their profile
information like delivery addresses. Overall, the project aims to provide
easy data flow, customer satisfaction, and less work through the developed
online platform.

Finally, the creation of a food delivery application utilising the MERN


stack resulted in a functioning and efficient system for ordering and
delivering meals. The software allows users to explore menus and place
orders thoroughly. while the restaurant can handle orders and change
menu items in real-time.

45
Planning, design, execution, and testing were all part of the
development process. The needs were identified and analysed during the
planning stage, and a thorough project plan was prepared. Wireframes,
mockups, and a database structure were all created throughout the design
stage. The MERN stack was used for implementation, which provided a
robust and versatile set of tools for creating both the application's front-
end and back-end. A set of unit, integration, and acceptance tests was
performed throughout the testing stage to confirm that the system fulfilled
all criteria and was free of faults and mistakes.

The adoption of MongoDB as the application's database was especially


advantageous since it allowed f or quick data storage and retrieval and
provided a scalable solution that could manage massive volumes of data.
Furthermore, using ReactJS as the frontend framework enabled a dynamic
and interactive user experience with rapid rendering and enhanced speed.

Various testing methodologies, including unit, integration, and


acceptability testing, were used to test the application. These tests were
performed to confirm that the system satisfied all functional and non-
functional criteria and was bug and error-free. Several difficulties were
discovered throughout the testing phase, which were addressed and
resolved in future rounds of the development process. Overall, the testing
method was critical in guaranteeing the system's quality and dependability.

Reference:
1. Admin and V. all posts by Admin, “How to Send Data from React to
Node js Express + MySQL - Tuts Make,” Tuts Make, Oct. 30, 2022.
[Online]. Available:
2. https://www.tutsmake.com/how-to-send-data-from-react-to-node-js-
express-mysql/

3. “What is the meaning of ‘bodyParser.urlencoded({ extended: true }))’


and ‘bodyParser.json()’ in Express.js?,” Stack Overflow, Apr. 07, 2019.

46
[Online]. Available:
https://stackoverflow.com/questions/55558402/what-is-the-meaning-
of-bodyparser-urlencode d-extended-true-and-bodypar

4. A. Sen, “Node React Tutorial - How to connect React with backend


Node.js?,” codedamn news, Sep. 14, 2022. [Online]. Available:
5. https://codedamn.com/news/reactjs/how-to-connect-react-with-node-js

6. “What does `app.use(bodyParser.json())` do?,” Stack Overflow, Oct.


05, 2016. [Online].
7. Available: https://stackoverflow.com/questions/39870867/what-does-
app-usebodyparser-json-do

Challenges
Technical Challenges
1. Integration with multiple restaurants: Integrating with various
restaurants, each with their own menu, pricing, and availability.
2. Real-time tracking and updates: Providing real-time tracking and
updates on order status, delivery location, and estimated delivery
time.
3. Payment gateway integration: Integrating with payment gateways to
facilitate secure and efficient transactions.
4. Scalability and performance: Ensuring the system can handle a large
volume of orders and traffic without compromising performance.
5. Security and data protection: Protecting sensitive customer data, such
as payment information and personal details.

Logistics and Operational Challenges

47
1. Restaurant partnership and management: Building and maintaining
relationships with restaurants, managing menus, and ensuring
consistent quality.
2. Delivery logistics and fleet management: Managing a fleet of delivery
drivers, optimizing routes, and ensuring timely deliveries.
3. Order management and fulfillment: Managing orders, handling
cancellations, and ensuring accurate fulfillment.
4. Customer support and service: Providing excellent customer support,
handling complaints, and resolving issues.
5. Compliance with regulations and laws: Ensuring compliance with food
safety regulations, labor laws, and other relevant laws.

Business Challenges
1. Competing with established players: Competing with existing food
delivery services, such as GrubHub, UberEats, and DoorDash.
2. Acquiring and retaining customers: Attracting and retaining customers
in a crowded market.
3. Managing commission fees and revenue: Balancing commission fees
with revenue goals and ensuring profitability.
4. Maintaining restaurant relationships: Building and maintaining strong
relationships with restaurants to ensure a consistent and high-quality
offering.
5. Scaling the business: Scaling the business while maintaining quality,
efficiency, and profitability.
New feature to add

User-Facing Features
1. Personalized Recommendations: Implement a recommendation
engine that suggests restaurants and dishes based on users' order
history and preferences.
2. Real-time Order Tracking: Provide real-time updates on order status,
including preparation, pickup, and delivery.
3. In-App Chat Support: Offer in-app chat support for customers to
resolve issues or ask questions.
4. Restaurant Reviews and Ratings: Allow users to leave reviews and
ratings for restaurants and dishes.

48
5. Loyalty Program: Implement a loyalty program that rewards
customers for repeat orders or referrals.
6. Social Sharing: Allow users to share their orders on social media
platforms.
7. Order Scheduling: Enable users to schedule orders in advance.
8. Dietary Restrictions and Preferences: Allow users to filter restaurants
and dishes based on dietary restrictions and preferences.

Restaurant-Facing Features
1. Restaurant Dashboard: Provide a dashboard for restaurants to
manage their menu, orders, and customer interactions.
2. Order Management: Enable restaurants to manage orders, including
accepting, rejecting, or modifying orders.
3. Menu Management: Allow restaurants to update their menu, including
adding, removing, or modifying dishes.
4. Customer Insights: Provide restaurants with insights into customer
ordering habits and preferences.
5. Restaurant Analytics: Offer analytics and reporting tools for
restaurants to track sales, orders, and customer engagement.

Operational Features
1. Automated Dispatch System: Implement an automated dispatch
system to optimize delivery routes and reduce delivery times.
2. Real-time Traffic Updates: Integrate real-time traffic updates to
optimize delivery routes and reduce delivery times.
3. Delivery Driver Management: Provide tools for managing delivery
drivers, including tracking, routing, and communication.
4. Order Fulfillment Management: Implement a system for managing
order fulfillment, including tracking, inventory management, and
logistics.
5. Customer Service Tools: Provide customer service representatives
with tools to manage customer inquiries, issues, and feedback.

Payment and Security Features


1. Secure Payment Processing: Implement secure payment processing to
protect customer payment information.

49
2. Multiple Payment Options: Offer multiple payment options, including
credit cards, digital wallets, and online banking.
3. Transaction History: Provide customers with a transaction history,
including order details and payment information.
4. Refund and Cancellation Policy: Implement a refund and cancellation
policy to protect customers in case of issues with orders.

Other Features
1. Integrations with Third-Party Services: Integrate with third-party
services, such as Google Maps, to enhance the user experience.
2. Machine Learning and AI: Implement machine learning and AI to
optimize operations, improve customer experience, and enhance
decision-making.
3. Data Analytics and Reporting: Provide data analytics and reporting
tools to help restaurants and administrators make data-driven
decisions.

OUTPUT
Screenshots
Landing Page

50
Responsive View

Signup Page

51
Login Page

Menu List

52
Footer Image

53
Order Image

Payment Interface

54
My Orders

55
Admin Panel
Add Food

List of Foods
56
Orders

57

You might also like