Express中server和路由分离

当我新建一个express配置的应用时,会自动创建一套应用构架:

其中:

public放置静态的东西,css、image、js

routes放置路由

views放置模板

看一下appjs

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/users', user.list);


http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

如果应用多了配置也会很多,app.js就会显得很臃肿。当然需要routes和app.js分离。

app.get('/', routes.index);
app.get('/users', user.list);
//app.get('/users/*', user.any);
app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){
    res.send(req.params);
});

app.get('/form', function(req, res){
    res.render('form');
});

app.post('/formaction',function(req, res){
  console.dir(req.body);
  res.redirect('back');
});

app.put('/formaction',function(req, res){
  console.dir(req.body);
  res.redirect('back');
});

方法是这样:

app.js

这样写,取代原来的routes配置:

routes(app);//这里执行

routes里这样写

module.exports=function(app){

  app.get('/',function(req,res){
    res.render('index',{
      title:'首页'
    });
  });
//.......其它配置
};

 当然,其它模块路由可以分开写

users模块路由,可以写入routes下的users.js,内容:

/*
 * GET users listing.
 */
module.exports = function(app){
    app.get('/users', function(req, res){
        res.send("respond with a resource");
    });
    
    app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){
        res.send(req.params);
    });
};

app.js里可以这样调用

//......
var users = require("./routes/users");
users(app);
//......

当然这样如果模块多了,同样会造成app.js臃肿。

还有一种写法,就是在第一种方法的基础上修改,我们注意到var routes = require("./routes");默认引用的是routes下的index.js模块。可以以此做为全部路由的引用入口:

var users = require("./users"),
form = require("./form");

module.exports = function(app){
    users(app);
    form(app);
}

app.js中修改如下

var routes = require("./routes");
routes(app);
// users路由 //users(app); // form路由 //form(app);

 

 

posted @ 2013-01-14 10:32  穆乙  阅读(6190)  评论(2编辑  收藏  举报