我为我的express服务器设置了两个看起来非常接近的路由。它们基本上是相同的url,除了一个是post,一个是get,get有一个额外的路由参数(这是可选的)。现在这些看起来工作正常,但是如果我没有在get调用中添加可选参数,它会认为我正在尝试击中post。我也希望能够在不传递第二个可选参数的情况下调用get。让我向您展示我到目前为止所拥有的:
router.param('itemID', (req, res, next, itemID) => {
verbose("itemID=", itemID);
next();
});
router.param('navigationType', (req, res, next, navigationType) => {
if (!navigationType) {
next();
}
verbose("navigationType=", navigationType);
next();
});
router.route('/:itemID/navigations')
.post(controllers.addActivity)
.all(routes.send405.bind(null, ['POST']));
router.route('/:itemID/navigations/:navigationType')
.get(controllers.listActivities)
.all(routes.send405.bind(null, ['GET']));
routed.send405方法如下所示:
function send405(methods, req, res) {
res.set('Allow', methods.join(','));
res.status(405).json({
message: `Method '${req.method}' Not Allowed.`
});
}
所以现在的问题是,如果我在/blah123/navigations
上执行get,并且没有添加/:navigationType
变量,它会认为我正在尝试命中post方法。我是一个非常新的工作与此,并感谢任何帮助或见解。谢谢!
发布于 2016-06-28 01:04:30
当您声明一个路由时,比如说GET /admins/:id
,它将匹配到GET /admins/1
或GET /admins/john
的任何请求。但是当您只执行GET /admins
时,它将无法找到,因为您没有声明与该模式匹配的GET路由。
要使用此方法,您必须将navigationType
指定为可选参数,并首先放置GET请求,然后放置POST,如下所示。
router.route('/:itemID/navigations/:navigationType?')
.get(controllers.listActivities)
.all(routes.send405.bind(null, ['GET']));
router.route('/:itemID/navigations')
.post(controllers.addActivity)
.all(routes.send405.bind(null, ['POST']));
https://stackoverflow.com/questions/38058662
复制相似问题