How to separate the routes and models from app.js using NodeJS and Express

后端 未结 3 638
生来不讨喜
生来不讨喜 2021-01-30 04:13

I\'m creating an app using Node and Express. However, I can see it\'ll soon become difficult to manage all the routes that are placed inside app.js. I have placed

3条回答
  •  抹茶落季
    2021-01-30 05:02

    As of express 4.x Router is added to support your case.

    A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.

    Example from expressjs site:

    // routes/calendarRouter.js
    
    var express  = require('express');
    var router = express.Router();
    
    // invoked for any requested passed to this router
    router.use(function(req, res, next) {
      // .. some logic here .. like any other middleware
      next();
    });
    
    // will handle any request that ends in /events
    // depends on where the router is "use()'d"
    router.get('/events', function(req, res, next) {
      // ..
    });
    
    module.exports = router;
    

    Then in app.js:

    // skipping part that sets up app
    
    var calendarRouter = require('./routes/calendarRouter');
    
    // only requests to /calendar/* will be sent to our "router"
    app.use('/calendar', calendarRouter);
    
    // rest of logic
    

提交回复
热议问题