NodeJS Express multiple route file through one route file

前端 未结 2 651
抹茶落季
抹茶落季 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.");
    }
    

提交回复
热议问题