Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
Node.js middleware does not work properly

I have a module with Routes in it. I want to check the access before letting user move forward. In Routes module I have two routes and two access-check functions, that I'd like to use as middlewares:

const doesUserExist = (req, res, next) => {
    if (!users[req.params.id]) {
        res.send(`Такого пользователя не существует`);
        return;
    }
    next();
}

const doesCatExist = (req, res, next) => {
    if (!cats[req.params.id]) {
        res.send(`Такой кошечки не существует`);
        return;
    }
    next();
}

dbAccess.get('/users/:id', (req, res) => {
    const { name, age } = users[req.params.id];
    res.send(`Пользователь ${name}, ${age} лет`);
});

dbAccess.get('/cats/:id', (req, res) => {
    const { nickName, color } = cats[req.params.id];
    res.send(`Кошечка ${nickName}, ${color} цвет`);
});

Then I export these middlewares into main file and use them the following way:

app.use('/users/:id', doesUserExist);
app.use('/', dbAccess);

app.use('/cats/:id', doesCatExist);
app.use('/', dbAccess);

For no reason to me, only first middleware works. If I try to enter the id of cat that does not exist, I get an error TypeError: Cannot destructure property 'nickName' of 'cats[req.params.id]' as it is undefined., so second middleware does not working at all and no access-check happens. I created another Routes module with another route and middleware in it and used it in Main file too and it works:

app.use('/users/:id', doesUserExist);
app.use('/', dbAccess);

app.use('/cats/:id', doesCatExist);
app.use('/', dbAccess);

app.use('/testpage', doesHaveAccess);
app.use('/testpage', testPage);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

A request GET /cats/1

  • ignores the route app.use('/users/:id', doesUserExist), because the path does not match
  • takes the route app.use('/', dbAccess), because / matches every path
  • inside dbAccess
    • it ignores dbAccess.get('/users/:id', ...), because the path does not match
    • it takes dbAccess.get('/cats/:id', ...), because the path matches. This then leads to the error you observed, because cats[req.params.id] === undefined.
  • The route app.use('/cats/:id', doesCatExist) is never reached by that request.

You should write

app.use('/users/:id', doesUserExist);
app.use('/cats/:id', doesCatExist);
app.use('/', dbAccess);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda