gpt4 book ai didi

node.js - node-restify 父路径处理程序

转载 作者:太空宇宙 更新时间:2023-11-03 21:58:06 27 4
gpt4 key购买 nike

如果我有两条路径,比如说 /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) 来调用路由 one两个。注意事项:如果没有为某个类型注册路由,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');
});

通用处理程序(又名 Express 中的中间件)

由于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');
});

关于node.js - node-restify 父路径处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34918573/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com