【发布时间】:2021-05-21 09:50:58
【问题描述】:
我正在阅读这篇文章
在中间件部分,作者很好地解释了next()的好处。
写这个
var app = require("express")();
function checkLogin()
{
return false;
}
function logRequest()
{
console.log("New request");
}
app.get("/dashboard", function(httpRequest, httpResponse, next){
logRequest();
if(checkLogin())
{
httpResponse.send("This is the dashboard page");
}
else
{
httpResponse.send("You are not logged in!!!");
}
});
app.get("/profile", function(httpRequest, httpResponse, next){
logRequest();
if(checkLogin())
{
httpResponse.send("This is the dashboard page");
}
else
{
httpResponse.send("You are not logged in!!!");
}
});
app.listen(8080);
使用 next() 可以更简洁
var app = require("express")();
function checkLogin()
{
return false;
}
function logRequest()
{
console.log("New request");
}
app.get("/*", function(httpRequest, httpResponse, next){
logRequest();
next();
})
app.get("/*", function(httpRequest, httpResponse, next){
if(checkLogin())
{
next();
}
else
{
httpResponse.send("You are not logged in!!!");
}
})
app.get("/dashboard", function(httpRequest, httpResponse, next){
httpResponse.send("This is the dashboard page");
});
app.get("/profile", function(httpRequest, httpResponse, next){
httpResponse.send("This is the dashboard page");
});
app.listen(8080);
但我不明白的是:next() 如何知道它应该在 /dashboard 中还是在 /profile 中作为 next 路由处理程序?
【问题讨论】:
-
取决于请求路径。
next()使请求从一个中间件转到管道中的下一个中间件。下一个中间件是否执行,取决于请求路径。 -
@Yousaf,嗯,好吧,我明白这就是为什么 app.get("/*",) 当路径为 profile 时它会去 profile
标签: node.js express routes middleware