Search code examples
javascriptnode.jsroutesparameters

Problems with params with routing in NodeJS


I'm using routing in NodeJS and I'm trying with routers in other routers, let's see:
server.js:

const routerProyecto = require('./routes/proyecto').routerProyecto;
app.use('/api/auth',routerAuth);
app.use('/api/proyecto',routerProyecto);

proyecto.js:

routerProyecto.use("/:idProyecto/backlog",routerBacklog);
//...more post and get methods

backlog.js:

const routerBacklog = express.Router();
routerBacklog.get("/listarBacklog",async(req,res)=>{
    const { tokenProyePUCP } = req.cookies;

    try{
        const payload = jwt.verify(tokenProyePUCP, secret);
        console.log(payload);
        const { idProyecto} = req.params;
        console.log(req.params);
        console.log(`Llegue a recibir solicitud listar backlog con id de Proyecto :  ${idProyecto}`);
        const query = `
            CALL LISTAR_PRODUCT_BACKLOG_X_ID_PROYECTO(?);
        `;
        try {
            const [results] = await connection.query(query,[idProyecto]);
            res.status(200).json({
                backlog: results[0],
                message: "Backlog obtenido exitosamente"
            });
            console.log(`Se han listado el backlog para el proyecto ${idProyecto}!`);
            console.log(results);
        } catch (error) {
            console.error("Error al obtener los proyectos:", error);
            res.status(500).send("Error al obtener los proyectos: " + error.message);
        }
    }catch(error){
        return res.status(401).send(error.message + " invalid tokenProyePUCP token");
    }

})

The problem here is in params, this hasn't the idProyecto param.

{
  "backlog": [],
  "message": "Backlog obtenido exitosamente"
}

What can be the problem? Is it a bad practice to use a variable in the middle of the URL?


Solution

  • In nested routes, for getting params from the parent, you need to add { mergeParams: true } in the child router.

    backlogs.js

    const routerBacklog = express.Router({ mergeParams: true });
    ....