Full Post Page
 

Nodejs middleware Part-3

Category: NODE JS & Written by Admin On May-01-2025 14:40:32

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.

Comments

Hanna

May-06-2025 18:54:57

Our pleasure is read This it's very helpful


Share your thoughts about this post

Why Choose Us:

Experienced Instructors: Our team of experienced instructors are passionate about coding and dedicated to helping you succeed. With years of industry experience and a knack for teaching, they'll guide you every step of the way. Beginner-Friendly Content: Don't worry if you're new to coding. Our tutorials are designed with beginners in mind, starting from the fundamentals and gradually building up to more advanced topics. Updated Content: Coding is a rapidly evolving field, and we're committed to keeping our content up-to-date with the latest trends, technologies, and best practices. Community Support: Learning to code is more fun and effective when you're part of a supportive community. Join our online community forums to connect with fellow learners, share insights, and collaborate on projects. Get Started Today:



Recent Posts

Advance Js Fetch API Part-5

June-06-2025 21:23:08


Advance Js Promise Part-4

June-06-2025 11:35:05


Advance js oop part-3

June-06-2025 08:25:42


ExpressJs API With Image Crud-3

June-02-2025 21:09:41


NodeJs API-MVC-2

June-02-2025 10:56:22


ExpressJs API Crud-1

June-02-2025 10:27:58


ExpressJs Files upload

June-02-2025 10:15:40


NodeJS Cookie and CsrfToken

May-30-2025 19:20:40


ExpressJS Session

May-30-2025 19:14:29


ExpressJS NodeJs Crud Part-2

May-27-2025 21:52:18


ExpressJS NodeJS Crud Part-1

May-27-2025 21:33:30


ExpressJS Authentication

May-26-2025 17:11:41


NodeJS ExpressJS Files Upload

May-26-2025 16:53:29



Angular Introduction

May-13-2025 21:02:32



Advance Js part-1

May-12-2025 15:41:29