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.
Is it possible to employ the app.use(path, router) pattern with named parameters in the path? If so how do I get at that :pid named parameter?
When you set the router to use comments for /posts/:pid/comments/, you're effectively throwing away the :pid parameter, because that parameter isn't available in the routing function defined in comments.js. Instead, you should define this route inside posts.js:
router.get("/:pid/comments", function(req, res) {
res.send("all comments " + req.params.pid);
});
Naturally, one would expect more complex logic to be required, which should be defined in a separate file and required in posts.js:
var comments = require("comments");
router.use("/:pid/comments", function(req, res) {
comments.renderGet(req.params.what, req, res);
});
Define your logic in comments.js:
module.exports = {
renderGet: function(id, req, res) {
res.send("all comments " + id);
},
// ... other routes, logic, etc.
};