ExpressJs: Differentiation between two similar routes

I have two routes /api/persons/:personId
and /api/persons/contact
,where :personId
is an ObjectId.

When i am hitting api/persons/contactS
(with an ‘S’ character),it is hitting the API code for api/persons/:personId
instead of giving 404.

So how can i distinguish between the two routes.I want to restrict my code control upfront where i define my routes before giving the handle to controller.

Express depends
on
path-to-regexp

for parsing route paths, which supports specifying custom patterns
with placeholders:

app.get('/api/persons/:personId([\dA-Fa-f]+)', ...);

app.get('/api/persons/contact', ...);

You can also use
app.param()

to validate personId
when it might be used:

app.param('personId', function (req, res, next, id) {
    Persons.findById(id, function (err, person) {
        if (err)
            return next(err);
        if (!person)
            return next('route');

        req.person = person;
        next();
    });
});
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » ExpressJs: Differentiation between two similar routes

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录