WEEK 5:
Create a food delivery website where users can order food from a particular restaurant listed
in the website for handling http request and response using node js.
Users can order food from a particular restaurant, with HTTP request and response handling. We'll
create a custom module for handling restaurant data and orders, making the app more modular and
easier to maintain.
Set Up the Project
First, let’s create the directory and initialize the Node.js project.
# Create the project directory
mkdir food-delivery
# Navigate into the directory
cd food-delivery
# Initialize a Node.js project
npm init -y
# Install Express.js
npm install express
Create the Directory Structure
Create the Custom Module: restaurant.js
// restaurant.js - Custom module to handle restaurant data and orders
// Dummy data for restaurants and their menus
const restaurants = [
{
id: 1,
name: "Pizza Hut",
menu: [
{ id: 1, name: "Margherita Pizza", price: 8.99 },
{ id: 2, name: "Pepperoni Pizza", price: 10.99 },
]
},
{
id: 2,
name: "Domino’s",
menu: [
{ id: 3, name: "California Roll", price: 6.99 },
{ id: 4, name: "Tuna Sashimi", price: 12.99 },
]
},
];
// Function to get all restaurants
const getRestaurants = () => {
return restaurants;
};
// Function to get the menu of a specific restaurant by ID
const getMenu = (restaurantId) => {
const restaurant = restaurants.find(r => r.id === parseInt(restaurantId));
return restaurant ? restaurant.menu : null;
};
// Function to place an order
const placeOrder = (restaurantId, foodId, quantity) => {
const restaurant = restaurants.find(r => r.id === parseInt(restaurantId));
if (!restaurant) return { error: "Restaurant not found" };
const foodItem = restaurant.menu.find(item => item.id === parseInt(foodId));
if (!foodItem) return { error: "Food item not found" };
// Calculate the total price
const totalPrice = foodItem.price * quantity;
return {
restaurant: restaurant.name,
foodItem: foodItem.name,
quantity: quantity,
totalPrice: totalPrice.toFixed(2)
};
};
// Export the functions to be used in other files
module.exports = {
getRestaurants,
getMenu,
placeOrder,
};
Create the Server File (server.js)
In server.js, we'll import the custom restaurant.js module and set up routes for the app.
server.js
// Import required libraries
const express = require('express');
const path = require('path');
const { getRestaurants, getMenu, placeOrder } = require('./restaurant'); // Import custom
module
// Initialize Express
const app = express();
// Define the port
const port = 3000;
// Middleware to parse URL-encoded data (for form submissions)
app.use(express.urlencoded({ extended: true }));
// Serve static files like CSS
app.use(express.static(path.join(__dirname, 'public')));
// Route to display the homepage with a list of restaurants
app.get('/', (req, res) => {
const restaurants = getRestaurants();
let restaurantList = '<ul>';
restaurants.forEach(restaurant => {
restaurantList += `<li><a
href="/restaurant/${restaurant.id}/menu">${restaurant.name}</a></li>`;
});
restaurantList += '</ul>';
res.send(`<h1>Food Delivery</h1><h2>Choose a Restaurant</h2>${restaurantList}`);
});
// Route to get the menu of a specific restaurant
app.get('/restaurant/:id/menu', (req, res) => {
const menu = getMenu(req.params.id);
if (!menu) return res.status(404).send('Restaurant not found');
let menuList = `<h2>Menu for Restaurant ${req.params.id}</h2><ul>`;
menu.forEach(item => {
menuList += `<li>${item.name} - $${item.price}</li>`;
});
menuList += `</ul><form action="/order" method="POST">
<input type="hidden" name="restaurantId" value="${req.params.id}">
<label for="foodId">Food Item ID:</label>
<input type="text" name="foodId" required>
<label for="quantity">Quantity:</label>
<input type="number" name="quantity" min="1" required>
<button type="submit">Order</button>
</form>`;
res.send(menuList);
});
// Route to handle placing an order
app.post('/order', (req, res) => {
const { restaurantId, foodId, quantity } = req.body;
const order = placeOrder(restaurantId, foodId, quantity);
if (order.error) {
return res.status(404).send(order.error);
}
res.send(`
<h1>Order Confirmed</h1>
<p>You ordered ${order.quantity} x ${order.foodItem} from ${order.restaurant}. Total: $$
{order.totalPrice}</p>
<a href="/">Go back to the restaurant list</a>
`);
});
// Start the server
app.listen(port, () => {
console.log(`Food Delivery app is running at http://localhost:${port}`);
});
Create the CSS File (styles.css)
In the public folder, you can add a simple styles.css to make the website look nice.
public/styles.css
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f9;
}
h1 {
color: #4CAF50;
}
ul {
list-style-type: none;
padding: 0;
}
ul li {
margin: 10px;
font-size: 20px;
}
a{
text-decoration: none;
color: #4CAF50;
}
form {
margin-top: 20px;
}
input, button {
padding: 8px;
margin: 5px;
}
button {
background-color: #4CAF50;
color: white;
border: none;
}
button:hover {
background-color: #45a049;
}
Run the Server
Now, you can run your application.
node server.js
Your application should now be running at http://localhost:3000. You should see a list of
restaurants on the homepage, and clicking on a restaurant will show its menu. You can then order a
food item by entering the foodId and quantity.
Test the Application
1. Open the browser and navigate to http://localhost:3000
2. Click on a restaurant name (e.g., "Pizza Hut" or "Domino’s") to view the menu.
3. Enter a food item ID and quantity to place an order.
4. The order confirmation will display the details of the order (food item, quantity, total
price).
OUTPUT: