kcp kcp - 1 month ago 7
Javascript Question

Param as router - ExpressJS

I have routes like

:id/comments/
,
:id/otherRoute
etc.
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
:id/
and create
controller
globally for all routes?

Answer

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) => {
    somefunction()
    .then(() => {
        //some logic with param.id
        next();
    })
    .catch((error) => {
        next(error);
    });
});

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

Comments