NodeJS Express multiple route file through one route file

Source: https://stackoverflow.com/questions/41182313/nodejs-express-multiple-route-file-through-one-route-file?rq=1
https://stackoverflow.com/questions/6059246/how-to-include-route-handlers-in-multiple-files-in-express

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'));




If you want to put the routes in a separate file, for example routes.js, you can create the routes.js file in this way:
module.exports = function(app){

    app.get('/login', function(req, res){
        res.render('login', {
            title: 'Express Login'
        });
    });

    //other routes..
}
And then you can require it from app.js passing the app object in this way:
require('./routes')(app);
Have also a look at these examples

Không có nhận xét nào:

Is it okay to use both fetchpriority="high" and loading="eager" in img tag?

 https://stackoverflow.com/questions/77744344/is-it-okay-to-use-both-fetchpriority-high-and-loading-eager-in-img-tag Yes Fetchpriority and l...