kcp kcp - 1 year ago 105
Javascript Question

Param as router - ExpressJS

I have routes like

For these routes I need to create new controller.
For example:

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}))

Is there any way to use new router for routes
and create
globally for all routes?

Answer Source

What you need is to make a middleware so you can do the llogic for all the routes that have the :id param, for example:

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

There's also the possibility of using the param middleware in witch you can do stuff with the param:

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

You can see more about middlewares in this link: express middlewares

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download