【问题标题】:How to overload routes using node restify如何使用 node restify 重载路由
【发布时间】:2013-11-05 18:00:52
【问题描述】:

我正在使用node-restify 并试图重载 GET 路由 - 这可能吗? next()不应该调用下一个注册的匹配路由吗?

这是一个例子。关于为什么它不起作用的任何提示?

server.get "search", (req, res, next) ->
    query = req.params.q
    console.log 'first handler'
    return next() if not query?

    # implement search functionality... return results as searchResults

    res.send 200, searchResults
    next()

server.get "search", (req, res, next) ->
    console.log 'second handler'
    res.send 200, "foo"
    next()

我希望/search 输出“foo”,我希望/search?q=bar 输出与“bar”搜索词匹配的所有记录。

【问题讨论】:

    标签: node.js coffeescript restify


    【解决方案1】:

    我对 Restify 不是很熟悉,但它的工作方式肯定与 Express 不同。

    我使用它来工作:

    app.get('/search', function(req, res, next) {
      var q = req.params.q;
      if (! q) {
        return next('getsearchfallback');
      }
      res.send('bar');
    });
    
    app.get('search-fallback', function(req, res, next) {
      res.send('foo');
      next();
    });
    

    不过,我不确定是否应该这样做。

    【讨论】:

      【解决方案2】:

      @robertklep 很接近 - 你应该在路由中添加一个 name

      不支持express "route chain" syntax,但可以像这样实现相同的功能:

      server.get('/foo', function (req, res, next) {
        if (something()) {
          next('GetBar');
          return;
        }
      
        res.send(200);
        next();
      });
      
      server.get({
        path: '/bar',
        name: 'GetBar'
      }, function (req, res, next) {
        res.send(200, {bar: 'baz'));
        next();
      });
      

      https://github.com/mcavage/node-restify/issues/193

      【讨论】:

      • 嗯...现在我看看实现,它真的不一样。其实离它还很远。也许我会写一个插件...
      猜你喜欢
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 2017-12-13
      • 2015-12-28
      • 2017-04-20
      • 2012-05-27
      • 1970-01-01
      相关资源
      最近更新 更多