一個常見的模式是獨立的邏輯變成你從你的呼叫路由功能,可以在不同的文件
把這些
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