title: Express Router Prefix
body: <p>I am confused about how to properly set up API routing in my express app. What I would like to have is structured way to define routes without repeating myself. As a database I am using RethinkDB. For each model, let's say <code>Exercise</code> I have created a file in the <code>models</code> directory. These files only define the model / schema. I thought that each model also defines an endpoint for my API. Thus, I have created a <code>routes</code> folder in which I declare my routes in separate files, e.g. <code>exercises.js</code>. This is my directory structure:</p>
  
  <pre><code>root
  ├── app.js
  ├── bootstrap.js
  ├── routes
  │   ├── exercises.js
  │   ├── index.js
  │   └── ...
  ├── models
  │   ├── exercise.js
  │   └── ...
  └── ...
  </code></pre>
  
  <p>An example route file looks like this:</p>
  
  <pre><code>module.exports = (function() {
      'use strict';
  
      var router = express.Router();
  
      router.get('/exercises', getAllExercises);
      router.get('/exercises/:id', getExerciseById);
  
      return router;
  })();
  </code></pre>
  
  <p>As you can see I am repeating the route prefix <code>exercises</code>. This is a sub-prefix because all routes should start with <code>/api</code>. Is it possible to define in a prefix for a single router, so that I use <code>app.use('/api', [routers])</code> in the <code>app.js</code> and tell each router to have a different route prefix such as <code>/api/excursions/</code>? I am confused about my declaration and also ask for feedback. I think there is a better way to organize my API because with what I am doing right know I would also need to include all routes in the <code>app.js</code> to pass in all routes to the app as an array. This is my <code>app.js</code>:</p>
  
  <pre><code>var express = require('express');
  var bodyParser = require('body-parser');
  var app = express();
  
  var port = process.env.PORT || 3000;
  
  app.use(bodyParser.json());
  
  // API Routes
  var exercises = require(__dirname + '/routes/exercises');
  
  app.use('/api', [exercises]);
  
  // Start the server
  app.listen(port);
  console.log('Listening on port '+ port);
  </code></pre>
  
  <p>The array syntax was taken from the offical express <a href="http://expressjs.com/api.html#app.use" rel="noreferrer">documentation</a>.</p>