How to set default path (route prefix) in express?

node.jsExpress

node.js Problem Overview


Instead of doing path + '..' foreach route - how can I prefix every route?

My route shall be

/api/v1/user

What I don't want to do

var path = '/api/v1';
app.use(path + '/user', user);

What I want to do

 var app = express();
 app.setPath('/api/v1');
 app.use(..);

node.js Solutions


Solution 1 - node.js

Using Express 4 you can use Router

var router = express.Router();
router.use('/user', user);

app.use('/api/v1', router);

Solution 2 - node.js

If you are using Express 4 Router you can use route() method to set the path and create a chainable route handler

app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
  .put(function (req, res) {
    res.send('Update the book')
  });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionboopView Question on Stackoverflow
Solution 1 - node.jsExplosion PillsView Answer on Stackoverflow
Solution 2 - node.jsAndrew ChudinovskyhView Answer on Stackoverflow