Middleware क्या है
Middleware ऐसे functions हैं जो हर request पर आपके route से पहले order में चलते हैं, request और response बदलने में सक्षम।
In this page:
Syntax
app.use((req, res, next) => {
// modify req or res
next();
});
Middleware
एक middleware का signature (req, res, next) है। यह req या res modify कर सकता है, response खत्म कर सकता है, या control पास करने के लिए next call कर सकता है।
app.use से register करें। Built-in वालों में express.json और express.static शामिल हैं, और third-party वाले logging, CORS, और auth cover करते हैं।
Note:
next() भूल जाना requests को hang करा देता है।
उदाहरण: Middleware
const express = require("express");
const app = express();
app.use((req, res, next) => {
req.startedAt = Date.now();
console.log(req.method, req.url);
next();
});
app.use(express.json());
app.get("/", (req, res) => res.send("ok in " + (Date.now() - req.startedAt) + "ms"));
app.listen(3000);
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- next call करना भूल जाना
- routes के बाद middleware register करना
- एक response भेजने के बाद next call करना
चैप्टर सारांश
- Signature (req, res, next) है
- app.use इसे register करता है
- next control पास करता है
- Order matter करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: