Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Express export routes for organization?

Utilizing express.Router() for API calls to/from our application:

var express = require('express');
var app     = express();
var router  = express.Router();

router.use console.logs before every API call:

router.use(function(req, res, next) { // run for any & all requests
    console.log("Connection to the API.."); // set up logging for every API call
    next(); // ..to the next routes from here..
});

How do we export our routes to folder/routes.js and access them from our main app.js, where they are currently located:

router.route('/This') // on routes for /This
    // post a new This (accessed by POST @ http://localhost:8888/api/v1/This)
    .post(function(req, res) {
        // do stuff
    });

router.route('/That') // on routes for /That
    // post a new That (accessed by POST @ http://localhost:8888/api/v1/That)
    .post(function(req, res) {
        // do stuff
    });

...when we prefix every route with:

app.use('/api/v1', router); // all of the API routes are prefixed with '/api' version '/v1'
like image 608
Stacks Avatar asked Aug 29 '15 08:08

Stacks


2 Answers

In your new routes module (eg in api/myroutes.js), export the module.

var express     = require('express');
var router      = express.Router();

router.use(function(req, res, next) {
  console.log('Connection to the API..');
  next();
});

router.route('/example')
  .get(function(req, res) { });
  .post(function(req, res) { });


module.exports = router;

Then you can require the module in your main server/app file:

var express = require('express');
var app     = express();


var myRoutes = require('./api/myRoutes');

app.use('/api', myRoutes); //register the routes
like image 109
Tony Barnes Avatar answered Nov 14 '22 10:11

Tony Barnes


In your app.js file you can have the following:

//api
app.use('/', require('./api'));

In the folder api you can have 'index.js` file, where you can write something like this:

var express = require('express');
var router = express.Router();

//API version 1
router.use('/api/v1', require('./v1'));

module.exports = router;

In the folder v1 file index.js something like this:

var express = require('express');
var router = express.Router();

router.use('/route1', require('./route1'));
router.use('/route2', require('./route2'));

module.exports = router;

File route1.js can have the following structure:

var express = require('express');
var router = express.Router();

router.route('/')
    .get(getRouteHandler)
    .post(postRouteHandler);

function getRouteHandler(req, res) {
    //handle GET route here
}

function postRouteHandler(req, res) {
    //handle POST route here
}

module.exports = router;

route2.js file can have the same structure.

I think this is very comfortable for developing the node project.

like image 41
Edgar Avatar answered Nov 14 '22 09:11

Edgar