Middleware and API Basics: understanding middleware; built-in and custom middleware (body-parser, static files); CORS and environment variables

Middleware एक function है जो एक request के middle में चलता है, arriving और handled होने के बीच, और Express इसे हर चीज़ के लिए इस्तेमाल करता है: JSON bodies parse करना, static files serve करना, CORS से cross-origin requests allow करना, और आपके अपने custom checks run करना।

12 min read · 8 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Middle में होने वाला Work

जब एक request आपके Express API तक पहुँचती है, आपका route handler run होने से पहले अक्सर कई चीज़ें होनी चाहिए होती हैं: JSON body parse करना, check करना caller allowed है, request log करना। हर handler में यह सब cram करने की बजाय, Express middleware इस्तेमाल करता है, functions जो request processing के middle में चलते हैं।

Middleware Express के सबसे important ideas में से एक है, और यह parsing, static files, cross-origin access, और आपके अपने custom checks power करता है। यह closing backend lesson explain करता है middleware क्या है और common pieces जो आप हमेशा इस्तेमाल करेंगे, हर full-stack beginner को trip करने वाले एक के सहित: CORS।

Theory

Middleware क्या है

एक middleware एक function है जो (req, res, next) receive करता है और एक request के दौरान चलता है, आपके route handler से पहले (या इसके around)। यह request और response पढ़ या change कर सकता है, और फिर यह next middleware या handler को control pass करने के लिए next() call करता है (या यह खुद response end कर सकता है)।

आप middleware को app.use(...) से register करते हैं। यह order में चलता है, एक pipeline बनाते हुए जिसके through हर request flow करती है। यह आपको shared work factor out करने देता है, इसे एक बार, एक जगह पर करना, कई routes के लिए, repeat करने की बजाय। Parsing, logging, authentication, और error handling सब naturally middleware हैं।

Practical

Built-in Middleware और एक Custom एक

const express = require('express');
const cors = require('cors');
const app = express();

app.use(express.json());          // built-in: parse JSON bodies -> req.body
app.use(express.static('public')); // built-in: serve files from /public
app.use(cors());                   // allow cross-origin requests (Angular -> API)

// custom middleware: log every request, then pass control on
app.use((req, res, next) => {
  console.log(req.method, req.url);
  next();                          // MUST call next() to continue
});

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Formula

CORS: Full-Stack Beginner का Stumbling Block

यहाँ एक problem है जो आप ज़रूर hit करेंगे। FestConnect का Angular front end एक origin पर चलता है (मान लीजिए localhost:4200) और Express API दूसरे पर (localhost:3000)। Security के लिए, browsers एक page को एक different origin पर API call करने से block करते हैं जब तक API explicitly इसे allow नहीं करता। यही CORS (Cross-Origin Resource Sharing) है।

Symptom एक blocked cross-origin request के बारे में एक console error है, और fix है server पर cors middleware enable करना (app.use(cors())), जो वे headers भेजता है जो browser को बताते हैं API इस call को permit करता है। लगभग हर full-stack beginner इससे एक बार मिलता है; अब आप इसे instantly recognise करेंगे।

Theory

Environment Variables Secrets को Code से बाहर रखते हैं

आपके backend को configuration चाहिए जिसे hard-code नहीं होना चाहिए: database connection string, API keys, port। इन्हें source code में डालना insecure और inflexible है (.NET में web.config से same lesson याद कीजिए)।

Node convention एक .env file में stored environment variables है, process.env के through पढ़े जाते हैं (अक्सर dotenv package के साथ)। तो process.env.DB_URL database address hold करता है, code से और version control से बाहर रखा गया। यह same code को आपके laptop पर और live server पर अलग settings के साथ run होने देता है, और secrets को leak होने से रोकता है। Configuration environment में, code में नहीं।

Quiz

आपका Angular app localhost:4200 पर आपके Express API को localhost:3000 पर call करता है, और browser इसे एक cross-origin error से block करता है। Server पर fix क्या है?

  1. सारा code एक file में move कीजिए
  2. CORS middleware enable कीजिए (app.use(cors())) तो API cross-origin requests permit करने वाले headers भेजे
  3. Express से Angular पर switch कीजिए
  4. Route parameters delete कीजिए
Show the answer

CORS middleware enable कीजिए (app.use(cors())) तो API cross-origin requests permit करने वाले headers भेजे

Browser अलग origins (localhost:4200 से localhost:3000) के बीच requests block करता है जब तक server CORS (Cross-Origin Resource Sharing) से opt in न करे। cors middleware को app.use(cors()) से enable करना API को वे headers भेजने देता है जो browser को बताते हैं cross-origin call allowed है, error resolve करते हुए। Option A browser के origin check को address नहीं करता; files combine करना origins नहीं बदलता। Option C nonsense है: Angular वह front end है जो call कर रहा है, API का replacement नहीं। Option D unrelated है: route parameters का cross-origin blocking से कोई लेना-देना नहीं है। CORS एक browser security feature है, और server पर cors middleware enable करना standard fix है।

Think first

Browsers पहली जगह पर Cross-Origin Requests क्यों Block करते हैं?

CORS beginners को grief देता है। यह actually कौन सा security problem protect कर रहा है? फिर tap कीजिए।

Show the answer

यह users को MALICIOUS websites से protect करता है जो silently OTHER sites को requests भेजती हैं जहाँ user logged in है, एक attack जिसे रोकने के लिए 'same-origin policy' design की गई है। Imagine कीजिए आप एक tab में अपने bank में logged in हैं। Origin restrictions के बिना, एक malicious page जो आप दूसरे tab में visit करते हैं quietly आपके bank के API को requests भेज सकता है आपके logged-in session इस्तेमाल करते हुए, आपका data पढ़ते हुए या money move करते हुए, यह सब आपको जाने बिना, क्योंकि browser उन requests में आपके bank cookies attach कर देता। इसे रोकने के लिए, browsers SAME-ORIGIN POLICY enforce करते हैं: default से, एक origin (scheme + host + port) पर JavaScript एक DIFFERENT origin से responses नहीं पढ़ सकता। वह safety default exactly वजह है आपका Angular app port 4200 पर, default से, आपके API को port 3000 पर call नहीं कर सकता, browser इन्हें अलग origins treat करता है और read block करता है। CORS एक server के लिए OPT IN करने का controlled तरीका है: specific headers भेजकर (जो cors middleware add करता है), API browser को बताता है 'मैं इस origin से requests permit करता हूँ', तो आपके जैसे legitimate cross-origin calls allowed हैं जबकि random malicious वाले नहीं। तो CORS कोई obstacle नहीं है जो आपको annoy करने के लिए invent किया गया; यह वह mechanism है जो आपको safely एक security rule को relax करने देता है जो users को protect करने के लिए exist करता है। इसे समझना confusing error को एक obvious, one-line fix में बदल देता है, और एक real web-security principle सिखाता है। Block browser का user को protect करना है; CORS server का permission grant करना है।

Summary

Key takeaways

  • Middleware एक function है (req, res, next) जो request processing के दौरान चलता है; इसे app.use() से register कीजिए।
  • इसे control pass करने के लिए next() call करना पड़ता है, या यह खुद response end करता है; middleware एक pipeline में चलता है।
  • Built-in: express.json() JSON bodies parse करता है (req.body enable करते हुए); express.static() static files serve करता है।
  • CORS: browsers cross-origin requests block करते हैं (एक port पर Angular, दूसरे पर Express) जब तक API इसे allow न करे; fix app.use(cors()) है।
  • Same-origin policy जिसे CORS relax करता है exist करता है malicious sites को दूसरी sites call करने से रोकने के लिए जहाँ आप logged in हैं।
  • एक .env file में Environment variables (process.env के through पढ़े गए) config और secrets को code से बाहर रखते हैं।
  • Memory hook: middleware middle में चलता है; express.json parse करता है, cors cross-origin allow करता है, .env secrets hold करता है।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Introduction to Express.js and Server-Side Basics with Node.js

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati