Skip to content

app.use(path, router) matches but does not extract named parameters in path #2257

@phildow

Description

@phildow

I am trying to separate routes into individual files with the app.use('/', router) pattern employed by default in an express initialized application. For example:

var users = require('./routes/users');
// ...
app.use('/users', users);

I've added a posts router for a blog, which works fine:

var posts = require('./routes/posts');
// ...
app.use('/posts', posts);

However, I'm now adding comments subroutes on posts. I need to employ a named parameter in the path supplied to app.use so that I can identify the post in addition to the comment:

var comments = require('./routes/comments');
// ...
app.use('/posts/:pid/comments', comments);

The routes/comments.js file looks like:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
  res.send('all comments + ', req.params.pid);
});

// ...

A path such as /posts/1/comments/34 correctly matches and the callback in router/comments.js is executed, but req.params.pid is undefined.

It looks like this is intentional behavior after posting to stack overflow. I understand one workaround is to include the additional path matching in routes/posts.js itself and point the callbacks to a separate routes/comment.js file, but then I cannot use parallel router.verb constructions there.

I've also found that I can simply use /posts again as the base path when referencing the routers from the main application file:

app.use('/posts', posts);
app.use('/posts', comments);

and rely on priority matching and on more targeted matching in routes/comment.js, but that solution leads to ambiguity considering the above code.

May I suggest supporting this as a feature request? It allows for parallel code constructions in the two routes files and would behave intuitively.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions