我有一条这样定义的路线
router.route('/:id/organisers').get(HackathonControllers.getHackathonRoles());
现在,getHackathonRoles
是一个定义如下的 Controller :
function getHackathonRoles(role, req, res, next) {
console.log(role);
res.status(200).json({
message: `Successfully updated Hackathon ${hackathonId}, published status updated to ${hackathonPublishedStatus}`
})
}
我理想的做法是通过定义多个路由器端点来传递角色。像这样的东西:
router.route('/:id/organisers').get(HackathonControllers.getHackathonRoles(role='organiser'));
还有
router.route('/:id/volunteer').get(HackathonControllers.getHackathonRoles(role='volunteer'));
所以基本上我想重用 getHackathonRoles
方法,并希望避免为不同的角色重写相同的方法。理想情况下,我应该能够在 Controller 中使用 console.log(role)
。
到目前为止,这失败了,我收到错误:
router.route('/:id/organisers').get(_hackathonController2.default.getHackathonRoles(role = 'organiser'));
我该如何解决这个问题并保持干燥?我不想将参数合并到端点中,例如 /:id/?
并且参数类似于 role=organiser
或 角色=志愿者
等等
最佳答案
get
函数需要一个带有签名 (req, res, next)
的回调,因此您不能只传递任意参数并期望它起作用。相反,您必须调用一个自行返回此类函数的函数。
function getHackathonRoles(role) {
console.log(role);
return function(req, res, next) {
// do something with the role variable
// send a response using res.status(...).json(...)
});
}
router.route('/:id/organisers').get(getHackathonRoles('organiser'));
router.route('/:id/volunteer').get(getHackathonRoles('volunteer'));
关于node.js - 在 ExpressJS 中将参数从路由器传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44214724/