Bri*_*ett 20 javascript url-routing node.js express
我正在使用Node.js和Express编写API.我的API有以下格式的GET方法:
/api/v1/doSomething
/api/v1/doSomethingElse
我的代码看起来像这样:
var app = express();
...
var routes = require('./routes')
routes.attachHandlers(app, '/api/v1')
...
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)
}
...
module.exports.attachHandlers = function(app, context) {
    app.get(context + '/doSomething', doSomething)
    app.get(context + '/doSomethingElse', doSomethingElse)
}
...
实际上,我正在通过应用程序传递上下文路径/挂载点.但是,如果有人要编写如下的路线,那么上下文就会丢失:
app.get('/doFoo', foo)
而不是将API的那部分安装在/api/v1/doFoo它上面/doFoo.我想避免像这样绕过上下文路径.
app.use支持在可选的装载路径上安装中间件.我在网上看到了使用安装路径安装整个Express应用程序的参考资料app.use.这似乎是我想要做的事情,但我不知道该怎么做,或者它是否是我特定用例的最佳解决方案.
总结一下 - 我想默认安装带有特定前缀的app.get()路由.这样做的最佳方法是什么?
mar*_*rni 43
使用Express 4.0,路由器的任务更加清晰.您可以根据需要创建任意数量的路由器,以便对应用程序进行精心分区,然后使用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');
});
在执行此操作时,您必须注意处理路径的顺序.
| 归档时间: | 
 | 
| 查看次数: | 14771 次 | 
| 最近记录: |