In Node.js, middleware functions intercept incoming requests before they reach their final destination, such as route handlers, and can also process outgoing responses before they are sent back to the client. These functions have access to the request and response objects, and they can execute code, modify the request or response objects, end the request-response cycle, or call the next middleware in the stack using the next() function. Middleware functions are commonly used for tasks such as: Authentication and authorization: Verifying user credentials and permissions. Logging: Recording request details for debugging or monitoring. Data validation: Ensuring that request data meets specific criteria. Error handling: Catching and handling errors that occur during request processing. Request parsing: Processing request bodies, such as JSON or form data. CORS: Enabling cross-origin resource sharing. Middleware can be applied at the application level, route level, or error-handling level. Application-level middleware is executed for all requests, while route-level middleware is specific to certain routes. Error-handling middleware is used to handle errors that occur during request processing. EXPRESS WHAT IS middleware ?? EXPRESSJS MEN ======checck condition======> PAGE 1,2 AS VISITOR <============RESPONE============ PAGE 3,4 HTTPS://WWWW.WEBSITES.COM/SOMEPAGE .AUTHENTICATED USER .AUTHENTICATEDF AND ADMINISTRATOR .VALID age .SAVE LOG INFORMATION .MAINTENANCE MODE .ERROR handling middleware===> app.use((req,res,next)=>{ }); or multiple middleware==> app.use((req,res,next)=>{ next() }); route===> app.get('/about',(req,res)=>{ }) app.get('/GALLERY',(req,res)=>{ }) TYPE OF middleware .APPLICATION-LEVEL middleware, .route-LEVEL-middleware,.error-HANDING-middleware,.BUILT-IN middleware.THIRD-PARTY-middleware MORE INFORMATION https://expressjs.com/=>Guide=>writing middleware https://expressjs.com/en/guide/writing-middleware.html ==>FRESS INSTALL NODEJS folder mkdir foldername cd foldername npm init -y (writing run start name add nodemon) npm install npm install express npm i nodemon =>create js file app.js include here express & app. listen server 1.include express const express=require('express'); const app=express(); 3.make route here app.get('/',(req,res)=>{ res.send("<h2>Home Page</h2>") }); app.get('/about',(req,res)=>{ res.send("<h2>About Page</h2>") }); 2.include Server app.listen(3000, () => { console.log('App listening on port 3000!'); }); 1.APPLICATION-LEVEL middleware A. Middleware basic // NOTES use middleware alway before Route // middleware self app.use((req,res,next)=>{ // console.log("Hello from Middleware") // retun message IN CONSOLE TERMINAL // console.log(`${req.method}${req.url}`) // return method and url in consloe // print date also const d=new Date() // let this first console.log(`Date : ${d.getDate()} / ${d.getMonth()}`) //console.log(`Time : ${d.getHours()} / ${d.getMinutes()}`) next() }) B. Middleware with name const mymiddleware=(req,res,next)=>{ const d=new Date() console.log(`Date : ${d.getDate()} / ${d.getMonth()}`) next() } const secondmymiddleware=(req,res,next)=>{ next() } // run this middleware (for all route) app.use(mymiddleware) C. specifie call middleware (for particular route page link ) const mymiddleware=(req,res,next)=>{ const d=new Date() console.log(`Date : ${d.getDate()} / ${d.getMonth()}`) next() } add in your route only app.get('/spmiddle',mymiddleware,secondmymiddleware ,(req,res)=>{ res.send("<h2>sepical call middleware</h2>") }); 2.Route-level middleware use express Router method //add first route (add dont use app object replace router) const router =express.Router() router.use((req,res, next)=>{ console.log("Router-Level-middlware") next() }) NB:note runing this way for run route middleware after route ending route write this //app.use('/',router); // home page route app.use('/test',router); // not home page route this is nestest route 2.Error handling- middleware app.get('/spmiddle',(req,res)=>{ res.sen("<h2>sepical call middleware</h2>") // error kie h send =en }); 3.Error Handling.level middleware NB: A.This middleware use after end of route app.use((err,req,res, next)=>{ console.error(err.stack) // for seeing error res.status(500).send("Something is Broke") next() }) Result http://localhost:3000/spmiddle Something is Broke B.NB IF VISITOR OPEN UNKNOWN ROUTE THEN CREATE FOR THIS Middleware app.use((req,res)=>{ res.send("<h2> Error 404 pange not found </h2>") }) nb now open UNKNOWN page then showing 404 message for VISITOR 4.Built.level middleware NB this middleware made in expess already .expess.json() (use inside api) .expess.urlencoded() (using in html from data) .express.static() (for showing staic data like image video ,music,css file ,jsfile) 5. third party middleware https://expressjs.com/en/resources/middleware.html Middleware module Description body-parser Parse HTTP request body. compression Compress HTTP responses. multer Handle multi-part form data. response-time Record HTTP response time. serve-favicon Serve a favicon. serve-index Serve directory listing for a given path. serve-static Serve static files. session Establish server-based sessions (development only). timeout Set a timeout perioHTTP request processing. vhost Create virtual domains.
May-06-2025 18:54:57
Our pleasure is read This it's very helpful
June-06-2025 21:23:08
June-06-2025 11:35:05
June-06-2025 08:25:42
June-02-2025 21:09:41
June-02-2025 10:56:22
June-02-2025 10:27:58
June-02-2025 10:15:40
May-30-2025 19:20:40
May-30-2025 19:14:29
May-27-2025 21:52:18
May-27-2025 21:33:30
May-26-2025 17:11:41
May-26-2025 16:53:29
May-26-2025 16:50:59
May-13-2025 21:02:32
May-13-2025 17:46:23
May-12-2025 15:41:29