}
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);
这里的问题是有很多重复的代码,即我们不得不多次使用logRequest()和checkLogin()函数。这也使得更新代码变得困难。因此,为了解决这个问题,我们可以为这两条路径编写一条通用路径。
这是重写的代码:
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);
这里的代码看起来更清晰,更易于维护和更新。这里将前两个定义的路由处理程序称为中间件,因为它们不处理请求,而是负责预处理请求。
Express为我们提供了app.use()方法,该方法专门用于定义中间件。 app.use()方法可能看起来与app.all()类似,但它们之间存在很多差异,这使得app.use()非常适合于声明中间件。让我们看看app.use()方法是如何工作的:
app.use() 和 app.all() 的不同:
CALLBACK
app.use()只需要一个回调,而app.all()可以进行多次回调。
PATH
app.use()只查看url是否以指定路径开头,app.all()匹配完整路径。
这里有一个例子来说明:
app.use( "/product" , mymiddleware);
// will match /product
// will match /product/cool
// will match /product/fooapp.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()调用下一个中间件或路由处理程序,具体取决于接下来声明的那个。但是路由处理程序中的next()仅调用下一个路由处理程序。如果接下来有中间件,则跳过它。因此,必须在所有路由处理程序之前声明中间件。
这里有一个例子来说明:
var express = require('express');









