node-restify父路径处理程序

时间:2016-01-21 08:20:07

标签: node.js 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');
});

1 个答案:

答案 0 :(得分:2)

不幸的是,在解析中不支持这种“堕落路由”。执行与请求匹配的第一个路由处理程序。但是你有一些替代方法来实现给定的用例

命名为next来电

您可以调用next()来调用路由next(req.params.type)one,而不是在没有参数的情况下调用two。注意事项:如果没有为某种类型注册路线,则会发送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 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');
});