bho*_*bar 1 routing node.js express
我有一条这样定义的路线
router.route('/:id/organisers').get(HackathonControllers.getHackathonRoles());
现在,getHackathonRoles是这样定义的控制器,例如:
function getHackathonRoles(role, req, res, next) {
console.log(role);
res.status(200).json({
message: `Successfully updated Hackathon ${hackathonId}, published status updated to ${hackathonPublishedStatus}`
})
}
Run Code Online (Sandbox Code Playgroud)
我理想地要做的是通过定义多个路由器端点来传递角色。就像是:
router.route('/:id/organisers').get(HackathonControllers.getHackathonRoles(role='organiser'));
和
router.route('/:id/volunteer').get(HackathonControllers.getHackathonRoles(role='volunteer'));
因此,基本上我想重用该getHackathonRoles方法,并希望避免针对不同角色重写同一方法。理想情况下,我应该能够console.log(role)使用控制器。
到目前为止,这失败了,我得到了错误:
router.route('/:id / organisers')。get(_hackathonController2.default.getHackathonRoles(role ='organiser'));
我该如何解决并使它保持干态?我不想像这样将参数合并到端点中/:id/?,而参数像role=organiser或role=volunteer等。
该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'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1677 次 |
| 最近记录: |