简体   繁体   English

如何使用节点Restify重载路由

[英]How to overload routes using node restify

I'm using node-restify and am trying to overload a GET route - is this possible? 我正在使用node-restify并试图重载GET路由-这可能吗? Shouldn't next() call the next matching route registered? next()不应调用已注册的下一个匹配路由吗?

Here is an example. 这是一个例子。 Any hints as to why it wouldn't work? 关于它为什么行不通的任何提示?

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()

I'd expect /search to output "foo", and I'd expect /search?q=bar to output all records matching the "bar" search term. 我希望/search输出“ foo”,并且希望/search?q=bar输出所有与“ bar”搜索条件匹配的记录。

I'm not very familiar with Restify, but it certainly works differently than Express. 我对Restify不太熟悉,但是它的工作方式肯定不同于Express。

I got it to work using this: 我使用它来工作:

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();
});

I'm not sure if that's how things should be done, though. 不过,我不确定是否应该这样做。

@robertklep was close - you should just add a name to the route. @robertklep很接近-您应该在路线上添加一个name

The express "route chain" syntax isn't supported, but the same functionality can be accomplished like this: 不支持表达“路由链”的语法 ,但是可以像这样完成相同的功能:

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 https://github.com/mcavage/node-restify/issues/193

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM