📚 Node.js + Express.
js Beginner Notes (with Real-
Life Analogies)
🧱 1. What is Node.js?
➕ Definition:
• Node.js is a JavaScript runtime that allows you to run JS code outside the browser.
• It’s built on Chrome’s V8 engine and designed to be fast and efficient for building server-side
applications.
• It enables developers to use JavaScript to write backend/server-side code, something traditionally
done using languages like Python, PHP, or Java.
🧠 Real-life Analogy:
• Think of your browser as a kitchen.
• Node.js is like setting up your own kitchen at home, so you can cook (run code) without needing
Chrome or Firefox.
🔧 How it works:
• Node.js runs on Google Chrome's V8 JavaScript engine.
• Uses asynchronous (non-blocking) operations, which allows handling many operations at once —
great for real-time apps.
• Uses an event-driven model: When a task completes, Node.js is notified and continues.
⚙️ 2. What is Express.js?
➕ Definition:
• Express.js is a web application framework built on top of Node.js.
• It simplifies routing, middleware integration, server-side rendering, and much more.
🧠 Analogy:
• Node.js is your kitchen.
• Express is a smart assistant chef that helps you manage orders, cooking, and serving efficiently.
📦 Why Use Express?
• Simplifies server creation with cleaner APIs
• Handles routing, templating, and middleware easily
• Large community and plenty of support
1
🛠️ 3. Basic Node.js + Express Server
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Home Page');
});
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
🧠 Explanation:
• require('express') : Import express module
• express() : Create app instance from Express
• app.get('/') : Handle GET requests at root URL
• res.send(...) : Send text as response
• app.listen(...) : Start server and listen on port 3000
📌 What You Need:
• Node.js installed
• Basic knowledge of JavaScript and the terminal
📦 4. Initialize Project with npm and Install Express
npm init -y
npm install express
• npm init -y : Initializes project with default settings
• npm install express : Installs Express and adds it to package.json
📂 Creates:
• package.json : Holds metadata and dependencies
• node_modules/ : Folder with all installed packages
2
🏠 5. Serve HTML Files using Express
🗂️ Folder Structure:
my-app/
├── views/
│ ├── index.html
│ ├── about.html
│ └── contact.html
└── app.js
📄 Code:
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
📘 Explanation:
• res.sendFile(...) : Sends the full HTML page as a response
• path.join(...) : Creates platform-safe path (Windows/Linux/Mac)
• __dirname : Gives current directory of the script
📨 6. Handle Form Submissions (POST Requests)
📄 HTML Form:
<form action="/submit-form" method="POST">
<input name="name">
<input name="email">
<textarea name="message"></textarea>
<button>Send</button>
</form>
📄 Express Route:
app.use(express.urlencoded({ extended: true }));
app.post('/submit-form', (req, res) => {
const { name, email, message } = req.body;
3
res.send('Thank you!');
});
🧠 Explanation:
• express.urlencoded(...) : Middleware to read form data from req.body
• req.body : Contains the parsed form data
• POST request: Sent by the form to the backend
🗃️ 7. Save Form Data to MongoDB using Mongoose
📦 What is MongoDB?
• A NoSQL database storing documents (similar to JSON objects)
📦 What is Mongoose?
• ODM (Object Data Modeling) library for MongoDB and Node.js
npm install mongoose
📄 Code:
mongoose.connect(process.env.MONGO_URI);
const contactSchema = new mongoose.Schema({
name: String,
email: String,
message: String
});
const Contact = mongoose.model('Contact', contactSchema);
app.post('/submit-form', async (req, res) => {
await Contact.create(req.body);
res.send('Saved!');
});
🧠 Explanation:
• mongoose.connect(...) : Connects to MongoDB
• Schema : Defines structure of documents
• Model : Interface to interact with MongoDB
4
🔐 8. Hide Secrets with .env File
npm install dotenv
📄 .env:
MONGO_URI=mongodb+srv://...
PORT=3000
📄 app.js:
require('dotenv').config();
const PORT = process.env.PORT;
mongoose.connect(process.env.MONGO_URI);
📄 .gitignore:
.env
🧠 Why Use .env?
• Keeps sensitive info out of code
• Easy to change between dev/staging/production
• .env is never pushed to GitHub
🎨 9. Serve Static Files (CSS, JS, Images)
📂 Folder:
public/
├── css/style.css
├── js/script.js
└── images/logo.png
📄 Code:
app.use(express.static(path.join(__dirname, 'public')));
5
📄 HTML:
<link rel="stylesheet" href="/css/style.css">
<script src="/js/script.js"></script>
🧠 Explanation:
• Files are served directly from public/
• Use /css/... , /js/... paths in your HTML
🛡️ 10. Admin Panel to View Submissions
📄 admin.html:
<table id="submissions"></table>
<script>
fetch('/api/submissions')
.then(res => res.json())
.then(data => {/* display in table */})
</script>
📄 app.js:
app.get('/admin', (req, res) =>
res.sendFile(path.join(__dirname, 'views', 'admin.html')));
app.get('/api/submissions', async (req, res) => {
const data = await Contact.find();
res.json(data);
});
🧠 Explanation:
• /admin : Serves the admin page
• /api/submissions : Sends JSON data
• fetch() : Frontend calls backend and updates table
6
✅ Summary
Feature Done?
Node.js Basics ✅
Express Setup ✅
Serve HTML Files ✅
Handle Forms ✅
Save to MongoDB ✅
Hide secrets with .env ✅
Serve CSS/JS ✅
Admin Panel ✅