【问题标题】:Node.js matching the url patternNode.js 匹配 url 模式
【发布时间】:2013-10-07 15:23:14
【问题描述】:

我需要在简单的 node.js 中等效于以下 express.js 代码,我可以在中间件中使用它。我需要根据 url 进行一些检查,并希望在自定义中间件中进行。

app.get "/api/users/:username", (req,res) ->
  req.params.username

到目前为止,我有以下代码,

app.use (req,res,next)->
  if url.parse(req.url,true).pathname is '/api/users/:username' #this wont be true as in the link there will be a actual username not ":username" 
    #my custom check that I want to apply

【问题讨论】:

    标签: node.js express url-pattern


    【解决方案1】:

    你可以使用node-js url-pattern模块。

    制作图案:

    var pattern = new UrlPattern('/stack/post(/:postId)');
    

    根据 url 路径匹配模式:

    pattern.match('/stack/post/22'); //{postId:'22'}
    pattern.match('/stack/post/abc'); //{postId:'abc'}
    pattern.match('/stack/post'); //{}
    pattern.match('/stack/stack'); //null
    

    欲了解更多信息,请参阅:https://www.npmjs.com/package/url-pattern

    【讨论】:

    • 我想从 URI 中找到一个模式,因为我在 DB 中有多个模式存储,我想在微服务网关中授权每个 URL。
    【解决方案2】:

    一个技巧是使用这个:

    app.all '/api/users/:username', (req, res, next) ->
      // your custom code here
      next();
    
    // followed by any other routes with the same patterns
    app.get '/api/users/:username', (req,res) ->
      ...
    

    如果您只想匹配GET 请求,请使用app.get 而不是app.all

    或者,如果你只想在某些特定路由上使用中间件,你可以使用这个(这次在 JS 中):

    var mySpecialMiddleware = function(req, res, next) {
      // your check
      next();
    };
    
    app.get('/api/users/:username', mySpecialMiddleware, function(req, res) {
      ...
    });
    

    编辑另一种解决方案:

    var mySpecialRoute = new express.Route('', '/api/users/:username');
    
    app.use(function(req, res, next) {
      if (mySpecialRoute.match(req.path)) {
        // request matches your special route pattern
      }
      next();
    });
    

    但我看不出这比使用 app.all() 作为“中间件”要好。

    【讨论】:

    • 我在中间件中没有 app 对象。我也只想匹配 URL 模式。
    【解决方案3】:

    只需像在中间件的路由处理程序中一样使用请求和响应对象,如果您确实希望请求在中间件堆栈中继续,请调用 next()

    app.use(function(req, res, next) {
      if (req.path === '/path') {
        // pass the request to routes
        return next();
      }
    
      // you can redirect the request
      res.redirect('/other/page');
    
      // or change the route handler
      req.url = '/new/path';
      req.originalUrl // this stays the same even if URL is changed
    });
    

    【讨论】:

    • 我需要匹配这个模式“/api/users/:username”,而我不能通过简单的比较来做到这一点。
    • 您可以在req.path 上使用.split() 并检查是否有url[1] === 'api'url[2] === 'users' 等。
    • 是的,我能做到。我只是想知道是否有一些标准的方法可以做到这一点。任何节点库等。感谢到目前为止的帮助。
    • 并没有真正的标准方法来匹配 URL,大多数会使用正则表达式或开关,是否有理由将此路由放入中间件而不是路由?跨度>
    猜你喜欢
    • 2012-06-18
    • 2019-03-29
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2016-02-28
    • 2018-12-02
    相关资源
    最近更新 更多