node-restify 父路径处理程序



如果我有两个路径,假设/path/onepath/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');
});
不幸的是,

这种"通过路由"在 restify 中不受支持。执行与请求匹配的第一个路由处理程序。但是您有一些替代方案来实现给定的用例

命名next呼叫

调用

next(req.params.type)不是在没有参数的情况下调用next(),而是调用路由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 没有像 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');
});

相关内容

最新更新