Organize routes in Node.js

前端 未结 6 1876
攒了一身酷
攒了一身酷 2020-12-04 04:57

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

6条回答
  •  甜味超标
    2020-12-04 05:35

    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
    

提交回复
热议问题