Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organize routes in Node.js

I start to look at Node.js. Also I'm using Express. And I have a question - how can I organize web application routes? All examples just put all this app.get/post/put() handlers in app.js and it works just fine. This is good but if I have something more than a simple HW Blog? Is it possible to do something like this:

var app = express.createServer(); app.get( '/module-a/*', require('./module-a').urls ); app.get( '/module-b/*', require('./module-b').urls ); 

and

// file: module-a.js urls.get('/:id', function(req, res){...}); // <- assuming this is handler for /module-a/1 

In other words - I'd like something like Django's URLConf but in Node.js.

like image 869
NilColor Avatar asked Jan 05 '11 08:01

NilColor


People also ask

How do I Group A route in node JS?

You can use an npm moduleYou can group your middlewares as an array and pass it to the express-inject-middleware... Show activity on this post. in express 4 to grouping your routes, you should create some changes : seperate route files in multiple files like admin and front.

How do I use node JS routes folder?

Create Employee Route File in Node First, go to the server folder, create a new folder call it “routes”. Inside the routes folder, create a new file and name it “employees. js” where we specify our Employees Routes. So first we need to import a module that is “express” into the employees.

What are routes in node JS?

A route is a section of Express code that associates an HTTP verb ( GET , POST , PUT , DELETE , etc.), a URL path/pattern, and a function that is called to handle that pattern.


2 Answers

I found a short example in ´Smashing Node.js: JavaScript Everywhere´ that I really liked.

By defining module-a and module-b as its own express applications, you can mount them into the main application as you like by using connects app.use( ) :

module-a.js

module.exports = function(){   var express = require('express');   var app = express();    app.get('/:id', function(req, res){...});    return app; }(); 

module-b.js

module.exports = function(){   var express = require('express');   var app = express();    app.get('/:id', function(req, res){...});    return app; }(); 

app.js

var express = require('express'),     app = express();  app.configure(..);  app.get('/', ....) app.use('/module-a', require('./module-a'));     app.use('/where/ever', require('./module-b'));      app.listen(3000); 

This would give you the routes

localhost:3000/ localhost:3000/module-a/:id localhost:3000/where/ever/:id 
like image 159
Vegar Avatar answered Oct 06 '22 13:10

Vegar


Check out the examples here:

https://github.com/visionmedia/express/tree/master/examples

'mvc' and 'route-separation' may be helpful.

like image 44
TK-421 Avatar answered Oct 06 '22 12:10

TK-421