BASIC EXPRESS.JS
🚀 Express.js – Complete Core Notes
Architecture, Routing, Middlewares, JSON APIs aur Server Setup ka comprehensive visual guide.
1️⃣ Express.js Kya Hai?
Definition: Express.js Node.js ka ek minimal aur flexible web application framework hai jo backend server development aur APIs banane ke kaam ko asaan aur fast karta hai.
http module me manually URL parsing, status codes aur request stream handle karni padti hai. Express.js yeh saare complex kaam ready-made methods ke zariye kuch hi lines me solve kar deta hai.
- Node.js Ecosystem: Node.js ke upar ek abstraction layer provide karta hai.
- Fast Routing: Alag-alag HTTP requests (GET, POST, PUT, DELETE) ko cleanly map karta hai.
- Lightweight: Unnecessary heavy tools ke bina lightweight rehta hai, jisse performance high hoti hai.
2️⃣ Express.js Ke Core Features
- Robust Routing: Dynamic parameters aur paths ke sath URLs handle karta hai.
- Middleware Support: Request complete hone se pehle security checks, body parsing aur logging lagana asaan hota hai.
- Template Engines: EJS, Pug ya Handlebars ke sath dynamic HTML pages render kar sakta hai.
- RESTful API Ready: JSON payloads aur status codes return karna bilkul straightforward hota hai.
3️⃣ Project Setup & Installation
Naya project initialize karke Express install karne ka command:
npm init -y
npm install express
| Command | Kya Karta Hai |
|---|---|
npm init -y |
Project ke liye default package.json file banata hai. |
npm install express |
Express library ko node_modules me download karta hai. |
4️⃣ First Express Server
Ek file banayein server.js aur usme yeh code likhein:
const express = require('express');
const app = express();
// Root route
app.get('/', (req, res) => {
res.send("Hello Express Server!");
});
// Port 3000 par start karein
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Code Explanation:
app.get()→ Jab user browser se page open kare (GET request), tab yeh callback run hota hai.res.send()→ Browser ko text ya HTML content send karta hai.app.listen()→ Server ko specified port (3000) par start karta hai.
5️⃣ Routing (Different URLs Handle Karna)
Alag-alag pages ya endpoints ke liye multiple routes define kiye jaate hain:
app.get('/home', (req, res) => {
res.send("Welcome to Home Page");
});
app.get('/about', (req, res) => {
res.send("Welcome to About Page");
});
6️⃣ Middleware (Request-Response Lifecycle)
Definition: Middleware ek function hota hai jo request aane par aur response bhejne ke beech me execute hota hai.
// Custom Middleware
app.use((req, res, next) => {
console.log("Middleware executed for URL: " + req.url);
next(); // Agle route ya middleware ko call karta hai
});
next() call nahi karenge, toh request wahi ruk jayegi aur browser hamesha loading state me phans jayega.
7️⃣ Sending JSON Responses (API Development)
Frontend (React, Android, iOS) ko data bhejne ke liye res.json() method ka use hota hai:
app.get('/api/user', (req, res) => {
res.json({
id: 101,
name: "Rahul Sharma",
role: "Developer",
status: "Active"
});
});
// Click the button to inspect the API JSON response payload...
🔹 Quick Development Tips
- Body Parser: POST requests se incoming JSON body read karne ke liye hamesha
app.use(express.json())add karein. - Environment Ports: Production deployment ke waqt dynamic port use karein:
const PORT = process.env.PORT || 3000;. - Route Separation: Bade projects me routes ko clean rakhne ke liye
express.Router()ka use karein.