express.js中间件说明详解(2)

中间件内的next()调用下一个中间件或路由处理程序,具体取决于接下来声明的那个。但是路由处理程序中的next()仅调用下一个路由处理程序。如果接下来有中间件,则跳过它。因此,必须在所有路由处理程序之前声明中间件。

这里有一个例子来说明:

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);

现在我们看到了app.use()方法的唯一性以及它用于声明中间件的原因。

让我们重写我们的示例站点代码:

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);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/3b7d5833559bf30d58776d336b3067f9.html