Controllers for refactored code in Node - estermer/ericstermer.com GitHub Wiki

In order to keep code clean, readable, and in order, MVC is good way to set up the web application.

Controllers are a way to organize similar path routes. for example all app.get, post, puts, and deletes on '/example'

To do this, create a folder in your main called controllers

and create a js file in it.

touch controllers/example.js

in the js file you will copy and paste all relevant routes into it.

At the top add express, router, and any outside data store files:

var express = require('express');
var router = express.Router();
var data = require('../data.js'); <<note the double ..

and at the bottom:

module.exports = router;

Then change all your instances of app to router.

In your server you need to require the file in controllers folder:

var exampleController = require('./controllers/example.js');

and then you need to reroute all paths to the controllers file you made:

app.use('/example', exampleController);

now with the router set up, we should be able to remove all paths that are '/example' and change them to '/' in our example.js file.