HTTP Controllers

Serverside JavaScript is used in the http controllers of Enonic XP. Every Page, Part, Layout, Services, Controller Mappings etc. must have a controller.

An application may also contain an Application Controller.

JavaScript controllers are invoked from the portal by exporting functions matching the desired HTTP Method it implements. As such, any controller must explicitly declare one or more “exports” in order to handle requests: get, post, delete are examples of such methods.

A controller can also export a special function all which will handle requests with any HTTP method, unless there is a function exported for the specific method.

The appropriate function will automatically be invoked for every request sent to the controller.

Example usage

// Handles a GET request
exports.get = function(req) {}

// Handles a POST request
exports.post = function(req) {}

// Handles all requests, other than GET or POST which are handled by the functions above
exports.all = function(req) {}

A handler function receives a parameter with a request object, and returns a response object.

exports.get = function(request) {

  if (request.mode === 'edit') {
    // do something...
  }

  var name = request.params.name;
  log.info('Name = %s', name);

  return {
    body: 'Hello ' + name,
    contentType: 'text/plain'
  };

};