中间件 next() routeHandler

Middleware next() routeHandler

我正在阅读这篇文章

Middleware 部分,作者很好地解释了 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 路由处理程序中 ?

只需转到“路由器句柄列表”中的下一条路由即可。顺序非常重要,在您的示例中,路由器列表看起来像 GET /* (any thing) -> GET /* (any thing) -> GET /dashboard -> GET /profile.

您浏览器的请求是GET /profile,按顺序查看方法和路径:

匹配任何东西 -> 是的,做点什么,下一个

匹配任何东西 -> 是的,做点什么,下一个

匹配 GET /dashboard -> 否,不执行仪表板处理程序,检查数组中的下一个路由器。

匹配 GET /profile -> 是的,做点什么,调用 httpResponse.send -> 完成。

如果你在app.get("/*",路由之前注册一个路由来检查login,它将不检查登录

...
app.get("/secret", function(httpRequest, httpResponse, next){

        httpResponse.send("Tada!!!");
});

app.get("/*", function(httpRequest, httpResponse, next){

    if(checkLogin())
    {
        next();
    }
    else
    {
        httpResponse.send("You are not logged in!!!");
    }
})
...