【问题标题】:How to check the req.url path is existing in app?如何检查应用程序中是否存在 req.url 路径?
【发布时间】:2018-11-11 16:15:18
【问题描述】:

我在我的应用程序中使用 sequelizejs、nodejs。我知道这会检查 inbuild,但我想像 if() 条件一样手动检查。 下面是一些url路径

/user
/user/11d9b6130159 => user/:id
/user/11d9bdfg0159/sample => user/:id/sample

我想要的是,有中间件,必须在应用程序路由中检查当前 url,比如

if(url.parse(req.url).path === "/user"){
  //some action do
}

但我无法访问剩余的网址。请提出解决方法。谢谢

【问题讨论】:

    标签: node.js url routes sequelize.js middleware


    【解决方案1】:

    如果你真的想手动进行 URL 解析,那么方法可能是这样的:

    编辑:根据您的评论,我修改了示例代码(超过 3 个级别)。您可以根据需要轻松扩展它。

    const url = require('url');
    
    const path = ctx.request.href;
    const pathName = url.parse(path).pathname;
    const pathNameParts = pathName.split('/'');
    
    if (pathNameParts && pathNameParts[1] && pathNameParts[1] === 'user') {
        if (pathNameParts[2]) {
            const id = pathNameParts[2];    // :id is now defined
            if (pathNameParts[3] && pathNameParts[3] === 'sample') {
                if (pathNameParts[4]) {
                    const id2 = pathNameParts[4];   // :id2 is now defined
                    if (pathNameParts[5] && pathNameParts[5] === 'disable') {
                        // do some action for /user/:id/sample/:id2/disable
                    } else {
                        // do some action for /user/:id/sample/:id2
                    }           
                } else {
                    // do some action for /user/:id/sample
                }
            } else {
                // do some action for /user/:id
            }           
        } else {
            // do some action for /user
        }
    }
    

    所以我只会这样做,如果你真的想自己做解析。否则使用 express 路由器或 koa 路由器之类的东西。使用快速路由器会是这样的:

    app.use('/user/:id', function (req, res, next) {
      console.log('ID:', req.params.id);
      next();
    });
    

    【讨论】:

    • 假设 url 将是 '/user/11d9bdfg0159/sample/df45g4435/disable'.. 这不仅仅是 3 级 url。
    猜你喜欢
    • 2010-10-30
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2011-02-04
    相关资源
    最近更新 更多