'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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
