user3271960
user3271960

Reputation:

Express Controller Modularity

New to Node/Express, trying to figure out what the best way to make my server controllers organized and modular. I have app.js file with the following code.

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

// Launch Server
const PORT = process.env.PORT || 8888;

app.listen(PORT, function() {
  console.log('Server running on port ' + PORT + '!');
});

// Render Static Views from the Public Directory/Views
app.use('/', express.static(__dirname + '/public/views/'));

// API
// var foo = require(bar);

I want to keep all of my API logic in apiController.js then require it into my app.js. What's the best way to do this?

Example GET Endpoint

app.get('/api', function(req, res) {
  res.json({
    success: true,
    message: 'Hello World!'
  });
});

Here is my project structure: enter image description here

Upvotes: 0

Views: 329

Answers (3)

Prashanth Chandra
Prashanth Chandra

Reputation: 2692

I like David Fang's solution, but I would go one step further and create an Express 4 router for your API routes. They're very composable and modular, as they can act as both routers and middleware, can be nested and imported neatly.

app.js

var apiRouter = require('./controllers/apiController.js');
app.use('/api', apiRouter);

apiController.js

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

apirouter.get('/some/route', (req, res) => {
    // some code...
})

module.exports = apiRouter;

Documentation: http://expressjs.com/en/api.html#router

Upvotes: 1

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7237

This is how i do it

I have app/controllers/index which call register method each of the controller. Each controller has a register method that register its route with the app.

In controllers:

exports.register = function(app) {
    app.post('/login', login)
}

In controllers index.js or routes or whatever you want to name it.

require('../controllers/auth').register(app)
require('../controllers/registration').register(app)

and at the end, drops all other routes to 404.

Upvotes: 0

David Fang
David Fang

Reputation: 1787

Here's a simple method:

app.js

require('./controllers/apiController.js')(app);

apiController.js

module.exports = function(app) {
    app.get('/api/some/route', function(req, res) {
        // some code...
    }
}

Maybe this is not the best approach, but I have used it without problem in small apps.

Upvotes: 1

Related Questions