2016-01-21 98 views
2

如果我有两条路径,比如说/path/onepath/two,我不是都是先由父处理程序处理,然后由它们的特定处理程序处理。我怎样才能实现它。下面的代码将不起作用。他们的具体处理程序从不运行node-restify父路径处理程序

const restify = require('restify'); 
const app = restify.createServer(); 
app.get('/path/:type', function (req, res, next) { 
    console.log(req.params.type + ' handled by parent handler'); 
    next(); 
}); 

app.get('/path/one', function (req, res) { 
    console.log('one handler'); 
    res.end(); 
}); 

app.get('/path/two', function (req, res) { 
    console.log('two handler'); 
    res.end(); 
}); 

app.listen(80, function() { 
    console.log('Server running'); 
}); 

回答

2

不幸的是,这种“fall through routing”在restify中不支持。匹配请求的第一个路由处理程序被执行。但是,你有一些替代品来实现给定用例

命名next呼叫

与其说next()没有你打电话next(req.params.type)调用路由onetwo的参数。注意事项:如果没有注册类型的路由,restify会发送500个响应。

const restify = require('restify'); 
const app = restify.createServer(); 

app.get('/path/:type', function (req, res, next) { 
    console.log(req.params.type + ' handled by parent handler'); 
    next(req.params.type); 
}); 

app.get({ name: 'one', path: '/path/one' }, function (req, res) { 
    console.log('one handler'); 
    res.end(); 
}); 

app.get({ name: 'two', path: '/path/two' }, function (req, res) { 
    console.log('two handler'); 
    res.end(); 
}); 

app.listen(80, function() { 
    console.log('Server running'); 
}); 

通用处理器(又名中间件快递)

由于的RESTify有一个像快递没有安装功能的作用,我们需要手动从目前的路径提取type PARAM:

const restify = require('restify'); 
const app = restify.createServer(); 

app.use(function (req, res, next) { 
    if (req.method == 'GET' && req.route && req.route.path.indexOf('/path') == 0) { 
    var type = req.route.path.split('/')[2]; 

    console.log(type + ' handled by parent handler'); 
    } 

    next(); 
}); 

app.get('/path/one', function (req, res) { 
    console.log('one handler'); 
    res.end(); 
}); 

app.get('/path/two', function (req, res) { 
    console.log('two handler'); 
    res.end(); 
}); 

app.listen(80, function() { 
    console.log('Server running'); 
});