In the docs for the NodeJS express module, the example code has app.use(...)
.
What is the use
function and where is it defined?
As the name suggests, it acts as a middleware in your routing.
Let's say for any single route, you want to call multiple url or perform multiple functions internally before sending the response. you can use this middleware and pass your route and perform all internal operations.
syntax:
app.use( function(req, res, next) {
// code
next();
})
next is optional, you can use to pass the result using this parameter to the next function.
It enables you to use any middleware (read more) like body_parser
,CORS
etc. Middleware can make changes to request
and response
objects. It can also execute a piece of code.
app.use()
is an middleware method.
Middleware method is like a interceptor in java, this method always executes for all request.
Purpose and use of middleware:-
app.use(function middleware1(req, res, next){
// middleware1 logic
}, function middleware1(req, res, next){
// middleware2 logic
}, ... middlewareN);
app.use is a way to register middleware or chain of middlewares (or multiple middlewares) before executing any end route logic or intermediary route logic depending upon order of middleware registration sequence.
Middleware: forms chain of functions/middleware-functions with 3 parameters req, res, and next. next is callback which refer to next middleware-function in chain and in case of last middleware-function of chain next points to first-middleware-function of next registered middlerare-chain.
You can also create your own middleware function like
app.use( function(req, res, next) {
// your code
next();
})
It contains three parameters req
, res
, next
You can also use it for authentication and validation of input params to keep your
controller clean.
next()
is used for go to next middleware or route.
You can send the response from middleware
app.use()
handles all the middleware functions.
What is middleware?
Middlewares are the functions which work like a door between two all the routes.
For instance:
app.use((req, res, next) => {
console.log("middleware ran");
next();
});
app.get("/", (req, res) => {
console.log("Home route");
});
When you visit /
route in your console the two message will be printed. The first message will be from middleware function. If there is no next()
function passed then only middleware function runs and other routes are blocked.