Application Controller

An application can implement a controller to handle HTTP requests. This is done by adding a main.js JavaScript file at the root of the application (/src/main/resources/).

The HTTP requests are handled independent of any site or content, on a specific URL with the path /app/[app-id] (e.g. “/app/com.enonic.app.superhero”).

The main.js file acts as any other controller and may expose a function for each HTTP method that should be handled: GET, POST, etc. Or an all function to handle requests with any method. (see HTTP Controllers).

The function that handles the request receives the request object as a parameter and returns the response object .

The following is an example of an application controller, in main.js.

var mustache = require('/lib/xp/mustache');

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

    var view = resolve('my-page.html');
    var params = {
        appId: app.name,
        title: 'Hello world'
    };

    return {
        body: mustache.render(view, params),
        contentType: 'text/html'
    };
};

// Handles a POST request
exports.post = function (req) {
    var name = request.params.name;

    return {
        body: {'Hello': name},
        contentType: 'application/json'
    };
};

// Handles all other method requests
exports.all = function (req) {
    if (req.method === 'DELETE') {
        handleDelete(req);

    } else if (req.method === 'PUT') {
        handlePut(req);
    }

    return {
        body: {'Hello': name, 'Method': req.method},
        contentType: 'application/json'
    };
};

Assets

The asset files of an application (see Assets) are also available under the application controller URL.

For example, the asset in src/main/resources/assets/css/styles.css in application with name com.enonic.myapp can be requested with the URL /app/com.enonic.myapp/css/styles.css.