node-restify父path处理程序
如果我有两个path,比方说/path/one
和path/two
,而我不是由父处理程序首先处理,然后由它们的特定处理程序处理。 我怎样才能做到这一点。 下面的代码将不起作用。 他们的具体处理程序从不运行
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'); });
不幸的是,这种“通过路由select”不被支持。 匹配请求的第一个路由处理程序被执行。 但是你有一些实现给定用例的select
命名next
呼叫
而不是调用next()
而不调用next(req.params.type)
来调用one
或two
路由。 注意事项:如果没有路线注册typesrestify将发送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没有像express这样的挂载特性,我们需要手动从当前路由中提取type
参数:
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'); });