【问题标题】:Middleware next() routeHandler中间件 next() routeHandler
【发布时间】: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


【解决方案1】:

只需转到“路由器句柄列表”中的下一条路线即可。顺序非常重要,在您的示例中,路由器列表如下所示 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!!!");
    }
})
...

【讨论】:

    猜你喜欢
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    相关资源
    最近更新 更多