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

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

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

使用声明 | 英豪名录