一个常见的模式是独立的逻辑变成你从你的呼叫路由功能,可以在不同的文件
把这些
var express = require('express');
var app = express();
require('http').createServer(app).listen(3000);
app.use(express.logger());
app.use(express.bodyParser());
app.use(app.router);
app.set('views', __dirname + '/templates');
app.set('view engine', 'jade');
var myLib = require('lib/myLib.js');
// myLib will contain: module.exports = { foo:function(req, arg, callback){ ... } };
app.get('/', function(req, res){
myLib.foo(req, 'hello', function(err, result){
// this is passed into foo as `callback` and generally is called from foo
if(err){ return res.send(500) };
res.send(200, 'Foo was ' + result);
});
});
// edit - ways to structure this with app.render for a jade template
app.get('/jade1', function(req, res){
myLib.bar(req, res);
// it is now myLib.bar's responsibility to send a response with the `res` object,
// either with res.end, res.send, res.render, res.redirect or whatever
});
// my preferred way: (i usually try to keep my logic separated from req/res)
app.get('jade2', function(req, res){
var username = req.body.username;
myLib.getUser(username, function(err, result){
if(err){ return res.send(500) };
res.locals.foobar = 'hello world';
// res.locals.x is equivalent to passing {x:_} inline to render as below:
res.render('jade2', {user: result});
});
});
你也可以把整个路由功能在一个单独的文件,并要求它从应用程序.js,从而设置你的路线。我认为这是在默认设置明确的行为,我也认为这是证明以及[在快递例子(https://github.com/visionmedia/express/tree/master/examples/route-separation) – Plato
还只需将逻辑直接放入路由就可以了。一些缺点是,如果你想从别的地方调用这个函数,它的可重用性就会降低,并且它会让你的路线变得混乱。 – Plato
你会如何将它与由jade生成的html整合?例如来自快速工具生成的应用的默认索引页面。 顺便说太棒了答案,谢谢。 – xdaxdb