express.js中间件说明详解

2020-06-17 06:37:18易采站长站整理

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