Express.js 路由 - 将参数化 URL 限制在两个选项内
Express.js Routing - Restrict a parameterized URL within two options
我有几个 URL 端点,如下所示
/api/comments/approve?ids=<comment-ids>
和
/api/comments/reject?ids=<comment-ids>
我有一个 handler/controller 函数,它将处理对两个端点的请求,执行由 URL 的 approve/reject 部分标识的适当操作。
我希望在我的路由配置中有一个 URL 配置,它允许我参数化 URL,同时限制 [=23] 之间的参数=] 和 'reject',以便仅在向上述端点之一发出请求时调用处理程序。
/api/comments/:action[approve|reject]?ids=<comment-ids>
您可以使用正则表达式来捕获路由。
app.get(/^\/api\/comments\/(approve|reject)/, function(req, res, next) {
var action = req.params[0]; //will contain either approve or reject, anything else will return a 404.
var ids = req.query.ids;
if(!ids) return next(new Error('No ids present'));
});
或者你也可以像现在这样,但是使用app.param
来控制参数。
app.param('action', function (req, res, next, action) {
if(action !== 'approve' && action !== 'reject') {
return next(new Error('Action is neither approve or reject.'));
}
next();
});
app.get('/api/comments/:action', function() {
var action = req.params.action;
});
我有几个 URL 端点,如下所示
/api/comments/approve?ids=<comment-ids>
和
/api/comments/reject?ids=<comment-ids>
我有一个 handler/controller 函数,它将处理对两个端点的请求,执行由 URL 的 approve/reject 部分标识的适当操作。
我希望在我的路由配置中有一个 URL 配置,它允许我参数化 URL,同时限制 [=23] 之间的参数=] 和 'reject',以便仅在向上述端点之一发出请求时调用处理程序。
/api/comments/:action[approve|reject]?ids=<comment-ids>
您可以使用正则表达式来捕获路由。
app.get(/^\/api\/comments\/(approve|reject)/, function(req, res, next) {
var action = req.params[0]; //will contain either approve or reject, anything else will return a 404.
var ids = req.query.ids;
if(!ids) return next(new Error('No ids present'));
});
或者你也可以像现在这样,但是使用app.param
来控制参数。
app.param('action', function (req, res, next, action) {
if(action !== 'approve' && action !== 'reject') {
return next(new Error('Action is neither approve or reject.'));
}
next();
});
app.get('/api/comments/:action', function() {
var action = req.params.action;
});