如何在特定的path前缀上安装app.get()路由

我正在使用Node.js和Express编写一个API。 我的API有以下格式的GET方法:

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

我的代码看起来像这样:

server.js:

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

路线/ 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) } 

路线/一些-route.js

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

有效地,我通过应用程序传递上下文path/挂载点。 如果有人写下如下的路线,上下文将会丢失:

 app.get('/doFoo', foo) 

而不是安装在/api/v1/doFoo上的那部分API在/doFoo 。 我想避免像这样传递上下文path。

app.use支持在可选的安装path上安装中间件。 我已经看到在线参考使用app.use将整个Express应用程序安装在安装path上。 这似乎是我想做的事情,但我不知道该怎么做,或者如果这是我的特殊用例的最佳解决scheme。

总结一下 – 我想默认使用特定的前缀装载我的app.get()路由。 这样做的最好方法是什么?

我认为快速命名空间将为此工作。

使用Express 4.0,使用路由器的任务要简单得多。 您可以创build尽可能多的路由器,以便很好地分区您的应用程序,然后使用app.use()附加它们。 例如:

myapp.js

 var express = require("express"), router = express.Router(), app = express(), port = 4000; // Here we declare our API which will be visible under prefix path router.get('/', function (req, res) { console.log("request to subspace hello"); res.send({ message: "Hi from subspace /api/v1/"}); }); // we attach our routes under /api/v1 app.use('/api/v1', router); // here we have direct, root-level routing app.get('/', function (req, res) { console.log("request to rootspace hello"); res.send({message: "Hi from root /"}); }); app.listen(port); console.log("App active on localhost:" + port); 

然后运行

 node myapp.js 

并参观

 http://localhost:4000 and http://localhost:4000/api/v1 

以下是在Express 3中安装路线的一个工作示例:

./snipe3app.js

 var express = require('express'); var app = module.exports = express(); app.get('/subapp', function (req, res) { res.send('You are on the /sub/subapp page.'); }); 

./app.js

 var express = require('express'), http = require('http'), subApp = require('./snipe3app'), app = express(); app.use(express.favicon()); app.use(express.bodyParser()); app.use(app.router); app.use('/sub', subApp); app.get('/', function (req, res) { res.send('You are on the root page'); }); http.createServer(app).listen(3000, function(){ console.log('Express server listening on port 3000. Point browser to route /secure'); }); 

这样做时,您必须注意处理路线的顺序。