Nodejs/Expressjs app structure

后端 未结 3 1613
猫巷女王i
猫巷女王i 2020-12-12 14:58

Say i have this code to separate routes in expressjs:

module.exports = function(express,app,client) {

    app.get(\'/\', function(req,res,next) {
               


        
相关标签:
3条回答
  • 2020-12-12 15:14

    How about express-train ? i have been using it lately, and it plays well with complex app structures.

    0 讨论(0)
  • 2020-12-12 15:20

    In the expressjs download package, there is a folder called "mvc". The author provides a good example for a tiny&efficient mvc structure. Going through the code, you will get much inspiration.

    0 讨论(0)
  • 2020-12-12 15:24

    There is a similar question here which you should read: How to structure a express.js application?

    1) All your query logic should be put in models (modules that reside in /models for example)

    2) Separate all your routes (controllers) into modules (and put them in /routes for ex) By routes I mean for example: - all the logic for "Users" routes go into /routes/users.js

    Try to keep you app as MVC-ish as possible.

    Small example for your app above:

    app.js

    // configuration for express etc
    require('./routes/index')(app)
    

    routes/index.js

    var model = require("../models/users.js");
    
    module.exports = function (app) {
    
      app.get('/', function (req, res, next) {
        model.get_recent(function (err, results) {
          // do stuff with your results
          res.render('index');
        });
      });
    
    }
    

    models/users.js

    module.exports = {
      get_recent: function(callback) {
        var query = "SELECT * FROM users LIMIT 10";
        database.query(query, callback);
      }
    }
    
    0 讨论(0)
提交回复
热议问题