Home > Software engineering >  Node.js middleware does not work properly
Node.js middleware does not work properly

Time:05-24

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

CodePudding user response:

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);
  • Related