Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Moving route logic out of app.js

Moving route logic out of app.js

Problem

I'm designing an app with node.js and Express, and I was wondering if it was possible to move certain routing logic out of the app.js file. For exapmle, my app.js currently contains:

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

Is there a way to move this logic out of the app.js file, and only have something like:

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

such that all GET requests would be processed by routes.get and all POST requests processed with routes.post?

Problem courtesy of: rahulmehta95

Solution

You could pass a regular expression as the Route definition:

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

This would match anything. However, if you simply want to move your route definitions outside of your main app.js file, it is much clearer to do something like this:

app.js

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

...

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

routes.js

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

This way, you're still using Express' built-in routing, rather than re-rolling your own (as you'd have to do in your example).

Solution courtesy of: josh3736

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Moving route logic out of app.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×