从app.js移出路线逻辑

时间:2012-07-15 16:59:48

标签: node.js express

我正在设计一个带有node.js和Express的应用程序,我想知道是否可以将某些路由逻辑移出app.js文件。为了exapmle,我的app.js目前包含:

app.get('/groups',routes.groups);
app.get('/',routes.index);

有没有办法将这个逻辑移出app.js文件,只有类似的东西:

app.get('/:url',routes.get);
app.post('/:url",routes.post);

所有GET个请求都会由routes.get处理,所有POST个请求都会使用routes.post处理?

2 个答案:

答案 0 :(得分:5)

您可以传递正则表达式作为路径定义:

app.get(/.+/, someFunction);

这可以匹配任何东西。但是,如果您只想将路径定义移到主app.js文件之外,那么执行以下操作会更清楚:

<强> app.js

var app = require('express').createServer();

...

require('routes').addRoutes(app);

<强> routes.js

exports.addRoutes = function(app) {
    app.get('/groups', function(req, res) {
        ...
    });
};

通过这种方式,您仍然使用Express的内置路由,而不是重新自行编辑(就像您在示例中所做的那样)。

答案 1 :(得分:0)

完全披露:我是下面提到的节点模块的开发人员。

有一个节点模块可以满足您的需求(并且最终会做更多)。它提供基于约定优于配置的自动路由。模块名称是honey-express,但目前处于alpha开发状态,但在NPM上尚未提供(但您可以从https://github.com/jaylach/honey-express的源代码处获得。

它是如何工作的一个简短例子:(请注意这个coffeescript)

# Inside your testController.coffee file. Should live inside /app/controllers
honey = require 'honey-express'

TestController = new honey.Controller
    index: ->
        # @view() is a helper method to automatically render the view for the action you're executing. 
        # As long as a view (with an extension that matches your setup view engine) lives at /app/views/controller/actionName (without method, so index and not getIndex), it will be rendered.
        @view()
    postTest: (data) ->
        # Do something with data

现在,在app.js文件中,您只需设置一些简单的配置:

# in your app.configure callback...
honey.config 'app root', __dirname + '/app'
app.use honey.router()

现在,只要有请求进入,honey就会自动查找具有指定路由的控制器,然后查找匹配的操作..例如 -

  • / test将自动路由到index / getIndex()方法 testController
  • /会自动路由到homeController的index / getIndex()方法(默认控制器是home),如果存在的话
  • 如果http方法是POST,
  • / test / test将自动路由到testController的postTest()方法。

正如我所提到的,该模块目前处于alpha状态,但是自动路由工作非常好,现在已经在两个不同的项目上进行了测试:)但是由于它是在alpha开发中,因此缺少文档。如果您决定走这条路,您可以查看我在github上的示例,查看代码,或联系我,我很乐意帮助:)

编辑:我还应该注意,honey-express确实需要最新的(BETA)版本的express,因为它使用的是2.x表达中不存在的功能。