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.

varmustache=require('/lib/xp/mustache');// Handles a GET requestexports.get=function(req){varview=resolve('my-page.html');varparams={appId:app.name,title:'Hello world'};return{body:mustache.render(view,params),contentType:'text/html'};};// Handles a POST requestexports.post=function(req){varname=request.params.name;return{body:{'Hello':name},contentType:'application/json'};};// Handles all other method requestsexports.all=function(req){if(req.method==='DELETE'){handleDelete(req);}elseif(req.method==='PUT'){handlePut(req);}return{body:{'Hello':name,'Method':req.method},contentType:'application/json'};};