Param作为路由器 - ExpressJS

时间:2016-10-21 10:47:36

标签: javascript node.js express typescript

我有:id/comments/:id/otherRoute等路线。 对于这些路线,我需要创建新的控制器。 例如:

let id: number = +req.params["id"];
new controller(id).getComments().then(comments => {
    res.json(response("error", {comments: comments}))
}).catch((error) => {
    res.json(response("error", {error: error}))
})

有没有办法为路由:id/使用新路由器并为所有路由全局创建controller

1 个答案:

答案 0 :(得分:2)

您需要制作一个中间件,以便为所有具有:id param的路由执行llogic,例如:

app.use('/something/:id', (req, res, next) => {
    //some code logic
    //error handling
    if(error){ next(error); }
    else { next(); }
});

还有可能使用param中间件,你可以用param做事:

app.param('id', (req, res, next, id) => {
    somefunction()
    .then(() => {
        //some logic with param.id
        next();
    })
    .catch((error) => {
        next(error);
    });
});

您可以在此链接中查看有关中间件的更多信息:express middlewares