NodeJS Express multiple route file through one route file

前端 未结 2 652
抹茶落季
抹茶落季 2020-12-31 23:59

I am learning NodeJS. I have a nodeJS API project. I want to use version in routes so i created following folder structure.

application/    
    --app.js
            


        
相关标签:
2条回答
  • 2021-01-01 00:52

    You should create express instance once and pass it into all modules.

    route.js file

    //initialize
    var express = require('express');
    var router = express.Router();
    
    router.get('/', function(req, res){    
        res.send("Welcome to Node JS V1");
    });
    
    //modules
    require('./users')(router);
    require('./sessions')(router);  //added for explaination
    require('./comments')(router);  //added for explaination
    
    //export
    module.exports.router = router;
    

    module file (any module users, comments etc)

    //initialize
    module.exports = function (router) {
        router.get('/users', users);
    }
    
    //APIs
    function users(req, res) {    
        res.send("Get all users.");
    }
    
    0 讨论(0)
  • 2021-01-01 00:54

    I'd do it a bit different than @Shaharyar

    routes.js

    var express = require('express');
    var router = express.Router();
    
    router.get('/', function(req, res) {
      res.send('Welcome to Node JS V1');
    });
    
    router.use('/users', require('./users').router);
    
    module.exports.router = router;
    

    users.js

    var express = require('express');
    var router = express.Router();
    
    router.get('/',function(req, res){    
      res.send('Get all users.');
    });
    
    router.post('/', function(req, res) {
      // Create user
      res.send('Some response.');
    });
    
    module.exports.router = router;
    

    To simplify it I'd drop the .router on module.exports and do.

    router.use('/users', require('./users'));
    

    Also the same for the route.js file, then in your server.js or wherever:

    router.use('/api/v1', require('./routes'));
    router.use('/api/v2', require('./routes2'));
    
    0 讨论(0)
提交回复
热议问题