How to effectively decouple your routing code
Dumb / Newb question ...
I am researching / working on an API in Node / Express4 and I would like to split my routes into another module. I have the following code working, but I find it awkward to keep reusing the require ('express') statement ... Is there a way to move more code from the routes.js file to the server. js and still keep my .get and .post statements in the routes module? Thanks in advance!
server.js:
'use strict';
var express = require('express');
var routes = require('./routes');
var app = express();
app.use('/api', routes);
app.listen(3000, function() {
console.log('Listening);
});
routes.js
var express = require('express'); // how do I get rid of this line?
var router = express.Router(); // can I move this to server.js?
var apiRoute = router.route('');
apiRoute.get(function (req, res) {
res.send('api GET request received');
});
module.exports = router;
source to share
On a right way. It's actually great to reuse the operator var express = require('express');
every time you need it. Importing (requiring) modules is a cornerstone of modular development and allows you to maintain separation of concerns in your project files.
As far as adding routes modularly: the problem is that it routes.js
is misleading.
To modularly split routes, you must use multiple named modules <yourResource>.js
. These modules will contain all the routing code as well as any other configuration or functionality required. Then you attach them to app.js with:
var apiRoute = router.route('/api');
apiRoute.use('/<yourResource', yourResourceRouter);
For example, if you have a resource bikes
:
In app.js
or even a module api.js
:
var apiRoute = router.route('/api')
, bikeRoutes = require('./bikes');
apiRoute.use('/bikes', bikeRoutes);
Then in bike.js:
var express = require('express');
var router = express.Router();
var bikeRoutes = router.route('/');
bikeRoutes.get(function (req, res) {
res.send('api GET request received');
});
module.exports = bikeRoutes;
From there, it's easy to see that you can create many different resources and nest them all the time.
source to share