Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

express - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...