01 Project – Node.js / Express / MongoDB – Part 05 – Creating routers and controllers

Our application like any other has URL paths. The router is like a map of URL paths. Every route on the server will correspond to a function in a controller. Controllers are modules with different functions. They match with the corresponding routes.

A route correspond to a controller. The controller will render a view. The view has its own model.

Let’s create routes.js file within the server folder.

var express = require('express'),
  router = express.Router(),
  home = require('../controllers/home'),
  image = require('../controllers/image');
module.exports = function(app) {
  router.get('/', home.index);
  router.get('/images/:image_id', image.index);
  router.post('/images', image.create);
  router.post('/images/:image_id/like', image.like);
  router.post('/images/:image_id/comment', image.comment);
  app.use(router);
};

The express.Router() class is used to create modular, mountable route handlers. You can read more details at https://expressjs.com/en/guide/routing.html.
The next two lines assign each route (home and image) to each corresponding function in the controllers.
We export a module which will attach all the routes to the application instance.

In a route, the first parameter is a string (name of the route) which can contain variable values as subpaths.

/images/:image_id

images is the route.
:image_id is the subpath.

The second parameter of a route is a callback function.

Now we have to create the matching controllers. Within the controllers folder create the home.js and the image.js files.

The home.js file will look like is shown below:

module.exports = {
  index: function(req, res) {
    res.send('The home:index controller');
  }
};

Here we export an object that has a single function named index. Every route using Express requires the same signature used in this function. The first parameter of the function is a request object and the second parameter is a response object.

The image.js file will look like is shown below:

module.exports = {
  index: function(req, res) {
    res.send('The image:index controller ' + req.params.image_id);
  },
  create: function(req, res) {
    res.send('The image:create POST controller');
  },
  like: function(req, res) {
    res.send('The image:like POST controller');
  },
  comment: function(req, res) {
    res.send('The image:comment POST controller');
  }
};

The index function is defined the same as in the home controller and we also added image_id. The params is a property that is added to the request object via the urlencoded (part of the body parser module).

Next, we need to add routes(app); in the configure.js file to activate our routes. The configure.js file now looks like is shown below:

var path = require('path'),
  routes = require('./routes'),
  exphbs = require('express-handlebars'),
  express = require('express'),
  bodyParser = require('body-parser'),
  cookieParser = require('cookie-parser'),
  morgan = require('morgan'),
  methodOverride = require('method-override'),
  errorHandler = require('errorhandler');

module.exports = function(app) {
  app.use(morgan('dev'));
  app.use(bodyParser({
    uploadDir:path.join(__dirname, 'public/upload/temp')
  }));
  app.use(methodOverride());
  app.use(cookieParser('some-secret-value-here'));

  routes(app);

  app.use('/public/', express.static(path.join(__dirname, '../public')));
    if ('development' === app.get('env')) {
      app.use(errorHandler());
    }
  return app;
};

Now, you can access http://localhost:3300 or http://localhost:3300/images/imagetest. In both cases you will get a response.

Leave a Reply