Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda