Home >Web Front-end >JS Tutorial >Introduction to express.js middleware (with examples)
This article brings you an introduction to express.js middleware (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
New express developers are often confused about the difference between route handlers and middleware. So they are also confused about the difference between app.use(), app.all(), app.get(), app.post(), app.delete() and app.put() methods.
In this article, I will explain the difference between middleware and route handlers. And how to use app.use(), app.all(), app.get(), app.post(), app.delete() and app.put() methods correctly.
Route processing
app.use(), app.all(), app.get(), app.post(), app.delete() and app.put() all Is used to define routes. These methods are used to define routes. Routing is used to handle HTTP requests. A route is a combination of a path and a callback, executed when the requested path matches. Callbacks are called route handlers.
The difference between them is to handle different types of HTTP requests. For example: The app.get() method only handles get requests, while app.all() handles GET, POST and other requests.
Here is an example of how to define a route:
var app = require("express")(); app.get("/", function(req, res, next){ res.send("Hello World!!!!"); }); app.listen(8080);
Each route handler gets a reference to the request and response objects for the HTTP request currently being served.
Multiple route handlers can be executed for a single HTTP request. Here is an example:
var app = require("express")(); app.get("/", function(req, res, next){ res.write("Hello"); next(); }); app.get("/", function(req, res, next){ res.write(" World !!!"); res.end(); }); app.listen(8080);
Here the first handle writes some response and then calls next()
. next()
The method is used to call the next route handler that matches the path path.
The route handler must end the request or call the next route handler.
We can also pass multiple route handlers to app.all()
, app.get()
, app.post()
, app.delete()
and app.put()
methods.
Here's an example that demonstrates this:
var app = require("express")(); app.get("/", function(req, res, next){ res.write("Hello"); next(); }, function(req, res, next){ res.write(" World !!!"); res.end(); }); app.listen(8080);
Middleware is a callback that sits on top of the actual request handler. It takes the same parameters as the route handler.
To understand middleware, let's look at a sample site with dashboard
and profile
pages. To access these pages, users must be logged in. Requests for these pages are also logged.
Here is the code for the route handler for these pages:
var app = require("express")(); function checkLogin(){ return false; } function logRequest(){ console.log("New request"); } app.get("/dashboard", function(req, res, next){ logRequest(); if(checkLogin()){ res.send("This is the dashboard page"); } else{ res.send("You are not logged in!!!"); } }); app.get("/profile", function(req, res, next){ logRequest(); if(checkLogin()){ res.send("This is the dashboard page"); } else{ res.send("You are not logged in!!!"); } }); app.listen(8080);
The problem here is that there is a lot of duplicate code, i.e. we have to use logRequest()
multiple times and checkLogin()
function. This also makes it difficult to update the code. So, to solve this problem, we can write a common path for both these paths.
This is the rewritten code:
var app = require("express")(); function checkLogin(){ return false; } function logRequest(){ console.log("New request"); } app.get("/*", function(req, res, next){ logRequest(); next(); }) app.get("/*", function(req, res, next){ if(checkLogin()){ next(); } else{ res("You are not logged in!!!"); } }) app.get("/dashboard", function(req, res, next){ res.send("This is the dashboard page"); }); app.get("/profile", function(req, res, next){ res.send("This is the dashboard page"); }); app.listen(8080);
The code here looks cleaner and easier to maintain and update. The first two defined route handlers are called middleware here because they do not handle requests but are responsible for preprocessing requests.
Express provides us with the app.use() method, which is specifically used to define middleware. The app.use() method may look similar to app.all(), but there are many differences between them that make app.use() well-suited for declaring middleware. Let’s see how the app.use() method works:
The difference between app.use() and app.all():
CALLBACK
app. use() only requires one callback, while app.all() can make multiple callbacks.
PATH
app.use() only checks whether the url starts with the specified path, and app.all() matches the complete path.
Here's an example to illustrate:
app.use( "/product" , mymiddleware); // will match /product // will match /product/cool // will match /product/foo app.all( "/product" , handler); // will match /product // won't match /product/cool <-- important // won't match /product/foo <-- important app.all( "/product/*" , handler); // won't match /product <-- Important // will match /product/cool // will match /product/foo
NEXT()
next() within a middleware calls the next middleware or route handler, depending on the interface The one that comes down to declare. But next() in the route handler only calls the next route handler. If there is middleware next, skip it. Therefore, middleware must be declared before all route handlers.
Here's an example to illustrate:
var express = require('express'); var app = express(); app.use(function frontControllerMiddlewareExecuted(req, res, next){ console.log('(1) this frontControllerMiddlewareExecuted is executed'); next(); }); app.all('*', function(req, res, next){ console.log('(2) route middleware for all method and path pattern "*", executed first and can do stuff before going next'); next(); }); app.all('/hello', function(req, res, next){ console.log('(3) route middleware for all method and path pattern "/hello", executed second and can do stuff before going next'); next(); }); app.use(function frontControllerMiddlewareNotExecuted(req, res, next){ console.log('(4) this frontControllerMiddlewareNotExecuted is not executed'); next(); }); app.get('/hello', function(req, res){ console.log('(5) route middleware for method GET and path patter "/hello", executed last and I do my stuff sending response'); res.send('Hello World'); }); app.listen(80);
Now we see the uniqueness of the app.use()
method and why it is used to declare middleware.
Let us rewrite our sample site code:
var app = require("express")(); function checkLogin(){ return false; } function logRequest(){ console.log("New request"); } app.use(function(req, res, next){ logRequest(); next(); }) app.use(function(req, res, next){ if(checkLogin()){ next(); } else{ res.send("You are not logged in!!!"); } }) app.get("/dashboard", function(req, res, next){ res.send("This is the dashboard page"); }); app.get("/profile", function(req, res, next){ res.send("This is the dashboard page"); }); app.listen(8080);
This article is all over here. For more other exciting content, you can pay attention to the JavaScript video on the PHP Chinese website Tutorial column!
The above is the detailed content of Introduction to express.js middleware (with examples). For more information, please follow other related articles on the PHP Chinese website!