我正在设计一个使用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处理
发布于 2012-07-16 01:10:38
您可以传递一个正则表达式作为路由定义:
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的内置路由,而不是重新滚动您自己的路由(就像您在示例中必须做的那样)。
发布于 2012-07-16 01:14:49
完全公开__:我是下面提到的节点模块的开发者。
有一个节点模块可以做你想做的事情(并且最终会做得更多)。它为express提供了基于约定而非配置的自动路由。该模块的名称是蜜糖-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就会自动查找具有指定路由的控制器,然后查找匹配的操作。例如:
正如我所提到的,该模块目前处于alpha状态,但自动路由工作得很好,并且已经在两个不同的项目上进行了测试:)但由于它处于alpha开发阶段,文档缺失。如果您决定走这条路,您可以查看我在github上提供的示例,查看代码,或者联系我,我很乐意提供帮助:)
编辑:我还应该注意到,honey express确实需要最新的express (BETA)版本,因为它使用了express 2.x中没有的功能。
https://stackoverflow.com/questions/11493849
复制相似问题