Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to mount app.get() routes on a particular path prefix
    text
    copied!<p>I'm writing an API using Node.js and Express. My API has GET methods of the form:</p> <pre><code>/api/v1/doSomething /api/v1/doSomethingElse </code></pre> <p>My code is looking something like this:</p> <h2>server.js:</h2> <pre><code>var app = express(); ... var routes = require('./routes') routes.attachHandlers(app, '/api/v1') </code></pre> <h2>routes/index.js</h2> <pre><code>... module.exports.attachHandlers = function(app, context) { //get a list of all the other .js files in routes //for each route, require() it and call it myRoute myRoute.attachHandlers(app, context) } </code></pre> <h2>routes/some-route.js</h2> <pre><code>... module.exports.attachHandlers = function(app, context) { app.get(context + '/doSomething', doSomething) app.get(context + '/doSomethingElse', doSomethingElse) } ... </code></pre> <p>Effectively I'm passing the context path/mount point down through the app. If somebody were to write a route like the following, though, the context would be lost:</p> <pre><code>app.get('/doFoo', foo) </code></pre> <p>Rather than having that part of the API mounted on <code>/api/v1/doFoo</code> it's on <code>/doFoo</code>. I would like to avoid having to pass the context path around like this.</p> <p><a href="http://expressjs.com/api.html#app.use" rel="noreferrer">app.use</a> supports mounting middleware on an optional mount path. I have seen references online to mounting an entire Express application on a mount path using <code>app.use</code>. This seems like the sort of thing I want to do, but I'm not sure how to do it or if it's the best solution for my particular use case.</p> <p>To summarise - I want to mount my app.get() routes with a particular prefix by default. What's the best way of doing this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload