Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  195] [ 2]  / answers: 1 / hits: 16851  / 11 Years ago, tue, june 18, 2013, 12:00:00

I'm writing an API using Node.js and Express. My API has GET methods of the form:



/api/v1/doSomething
/api/v1/doSomethingElse


My code is looking something like this:



server.js:



var app = express();
...
var routes = require('./routes')
routes.attachHandlers(app, '/api/v1')


routes/index.js



...
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)
}


routes/some-route.js



...
module.exports.attachHandlers = function(app, context) {
app.get(context + '/doSomething', doSomething)
app.get(context + '/doSomethingElse', doSomethingElse)
}
...


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:



app.get('/doFoo', foo)


Rather than having that part of the API mounted on /api/v1/doFoo it's on /doFoo. I would like to avoid having to pass the context path around like this.



app.use supports mounting middleware on an optional mount path. I have seen references online to mounting an entire Express application on a mount path using app.use. 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.



To summarise - I want to mount my app.get() routes with a particular prefix by default. What's the best way of doing this?


More From » node.js

 Answers
126

I think express-namespace will work for this.


[#77561] Monday, June 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
montana

Total Points: 675
Total Questions: 86
Total Answers: 102

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
;